You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

namespace.py 3.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  2. #
  3. # Copyright 2020 Huawei Technologies Co., Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # ============================================================================
  17. """Define the namespace of parse."""
  18. import builtins
  19. from mindspore import log as logger
  20. class Namespace:
  21. """
  22. Base class of namespace for resolve variables.
  23. Args:
  24. name (str): The namespace's name.
  25. dicts (dict): A list of dict containing the namespace's variable.
  26. """
  27. def __init__(self, name, *dicts):
  28. self.name = name
  29. self.dicts = dicts
  30. def __contains__(self, name):
  31. for d in self.dicts:
  32. if name in d:
  33. return True
  34. return False
  35. def __getitem__(self, name):
  36. for d in self.dicts:
  37. if name in d:
  38. return d[name]
  39. raise NameError(name)
  40. def __repr__(self):
  41. return f'Namespace:{self.name}'
  42. class CellNamespace(Namespace):
  43. """
  44. Namespace for Cell object.
  45. Args:
  46. name (str): Valid module name, it can be imported.
  47. """
  48. def __init__(self, name):
  49. mod_dict = vars(__import__(name, fromlist=['_']))
  50. builtins_dict = vars(builtins)
  51. super().__init__(name, mod_dict, builtins_dict)
  52. def __getstate__(self):
  53. return (self.name,)
  54. def __setstate__(self, state):
  55. name, = state
  56. mod_dict = vars(__import__(name, fromlist=['_']))
  57. builtins_dict = vars(builtins)
  58. super().__init__(name, mod_dict, builtins_dict)
  59. class ClosureNamespace(Namespace):
  60. """
  61. Namespace for function closure.
  62. Args:
  63. fn (Function): A python function.
  64. """
  65. def __init__(self, fn):
  66. name = f'{fn.__module__}..<{fn.__name__}>'
  67. names = fn.__code__.co_freevars
  68. cells = fn.__closure__
  69. ns = dict(zip(names, cells or ()))
  70. super().__init__(name, ns)
  71. def __getitem__(self, name):
  72. d, = self.dicts
  73. try:
  74. return d[name].cell_contents
  75. except ValueError:
  76. raise UnboundLocalError(name)
  77. class ClassMemberNamespace(Namespace):
  78. """
  79. Namespace of a class's closure.
  80. Args:
  81. obj (Object): A python class object.
  82. """
  83. def __init__(self, obj):
  84. self.__class_member_namespace__ = True
  85. label = f'{obj.__module__}..<{obj.__class__.__name__}::{id(obj)}>'
  86. super().__init__(label, obj)
  87. def __getitem__(self, name):
  88. d, = self.dicts
  89. if name == "self":
  90. return d
  91. if name == "namespace":
  92. return self
  93. try:
  94. if hasattr(d, name):
  95. return getattr(d, name)
  96. return d.__dict__[name]
  97. except ValueError:
  98. raise UnboundLocalError(name)
  99. except KeyError:
  100. logger.info(f"'{d.__class__.__name__ }' object has no attribute or method: '{name}', so will return None.")
  101. raise AttributeError(name)