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.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. class Namespace:
  20. """
  21. Base class of namespace for resolve variables.
  22. Args:
  23. name (str): The namespace's name.
  24. dicts (dict): A list of dict containing the namespace's variable.
  25. """
  26. def __init__(self, name, *dicts):
  27. self.name = name
  28. self.dicts = dicts
  29. def __contains__(self, name):
  30. for d in self.dicts:
  31. if name in d:
  32. return True
  33. return False
  34. def __getitem__(self, name):
  35. for d in self.dicts:
  36. if name in d:
  37. return d[name]
  38. raise NameError(name)
  39. def __repr__(self):
  40. return f'Namespace:{self.name}'
  41. class CellNamespace(Namespace):
  42. """
  43. Namespace for Cell object.
  44. Args:
  45. name (str): Valid module name, it can be imported.
  46. """
  47. def __init__(self, name):
  48. mod_dict = vars(__import__(name, fromlist=['_']))
  49. builtins_dict = vars(builtins)
  50. super().__init__(name, mod_dict, builtins_dict)
  51. def __getstate__(self):
  52. return (self.name,)
  53. def __setstate__(self, state):
  54. name, = state
  55. mod_dict = vars(__import__(name, fromlist=['_']))
  56. builtins_dict = vars(builtins)
  57. super().__init__(name, mod_dict, builtins_dict)
  58. class ClosureNamespace(Namespace):
  59. """
  60. Namespace for function closure.
  61. Args:
  62. fn (Function): A python function.
  63. """
  64. def __init__(self, fn):
  65. name = f'{fn.__module__}..<{fn.__name__}>'
  66. names = fn.__code__.co_freevars
  67. cells = fn.__closure__
  68. ns = dict(zip(names, cells or ()))
  69. super().__init__(name, ns)
  70. def __getitem__(self, name):
  71. d, = self.dicts
  72. try:
  73. return d[name].cell_contents
  74. except ValueError:
  75. raise UnboundLocalError(name)
  76. class ClassMemberNamespace(Namespace):
  77. """
  78. Namespace of a class's closure.
  79. Args:
  80. obj (Object): A python class object.
  81. """
  82. def __init__(self, obj):
  83. label = f'{obj.__module__}..<{obj.__class__.__name__}::{id(obj)}>'
  84. super().__init__(label, obj)
  85. def __getitem__(self, name):
  86. d, = self.dicts
  87. try:
  88. return getattr(d, name)
  89. except ValueError:
  90. raise UnboundLocalError(name)