Evaluate the forward reference and return the value. If the forward reference cannot be evaluated, raise an exception.
(
self,
*,
globals=None,
locals=None,
type_params=None,
owner=None,
format=Format.VALUE,
)
| 99 | raise TypeError("Cannot subclass ForwardRef") |
| 100 | |
| 101 | def evaluate( |
| 102 | self, |
| 103 | *, |
| 104 | globals=None, |
| 105 | locals=None, |
| 106 | type_params=None, |
| 107 | owner=None, |
| 108 | format=Format.VALUE, |
| 109 | ): |
| 110 | """Evaluate the forward reference and return the value. |
| 111 | |
| 112 | If the forward reference cannot be evaluated, raise an exception. |
| 113 | """ |
| 114 | match format: |
| 115 | case Format.STRING: |
| 116 | return self.__forward_arg__ |
| 117 | case Format.VALUE: |
| 118 | is_forwardref_format = False |
| 119 | case Format.FORWARDREF: |
| 120 | is_forwardref_format = True |
| 121 | case _: |
| 122 | raise NotImplementedError(format) |
| 123 | if isinstance(self.__cell__, types.CellType): |
| 124 | try: |
| 125 | return self.__cell__.cell_contents |
| 126 | except ValueError: |
| 127 | pass |
| 128 | if owner is None: |
| 129 | owner = self.__owner__ |
| 130 | |
| 131 | if globals is None and self.__forward_module__ is not None: |
| 132 | globals = getattr( |
| 133 | sys.modules.get(self.__forward_module__, None), "__dict__", None |
| 134 | ) |
| 135 | if globals is None: |
| 136 | globals = self.__globals__ |
| 137 | if globals is None: |
| 138 | if isinstance(owner, type): |
| 139 | module_name = getattr(owner, "__module__", None) |
| 140 | if module_name: |
| 141 | module = sys.modules.get(module_name, None) |
| 142 | if module: |
| 143 | globals = getattr(module, "__dict__", None) |
| 144 | elif isinstance(owner, types.ModuleType): |
| 145 | globals = getattr(owner, "__dict__", None) |
| 146 | elif callable(owner): |
| 147 | globals = getattr(owner, "__globals__", None) |
| 148 | |
| 149 | # If we pass None to eval() below, the globals of this module are used. |
| 150 | if globals is None: |
| 151 | globals = {} |
| 152 | |
| 153 | if type_params is None and owner is not None: |
| 154 | type_params = getattr(owner, "__type_params__", None) |
| 155 | |
| 156 | if locals is None: |
| 157 | locals = {} |
| 158 | if isinstance(owner, type): |