Python typing._ForwardRef() Examples
The following are 12
code examples of typing._ForwardRef().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: typing.py From pydantic with MIT License | 6 votes |
def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]) -> Dict[str, Type[Any]]: """ Partially taken from typing.get_type_hints. Resolve string or ForwardRef annotations into type objects if possible. """ if module_name: base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__ else: base_globals = None annotations = {} for name, value in raw_annotations.items(): if isinstance(value, str): if sys.version_info >= (3, 7): value = ForwardRef(value, is_argument=False) else: value = ForwardRef(value) try: value = _eval_type(value, base_globals, None) except NameError: # this is ok, it can be fixed with update_forward_refs pass annotations[name] = value return annotations
Example #2
Source File: test_typing.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_forwardref_instance_type_error(self): fr = typing._ForwardRef('int') with self.assertRaises(TypeError): isinstance(42, fr)
Example #3
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_forwardref_instance_type_error(self): fr = typing._ForwardRef('int') with self.assertRaises(TypeError): isinstance(42, fr)
Example #4
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_forwardref_subclass_type_error(self): fr = typing._ForwardRef('int') with self.assertRaises(TypeError): issubclass(int, fr)
Example #5
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_forward_equality(self): fr = typing._ForwardRef('int') self.assertEqual(fr, typing._ForwardRef('int')) self.assertNotEqual(List['int'], List[int])
Example #6
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_forward_repr(self): self.assertEqual(repr(List['int']), "typing.List[_ForwardRef('int')]")
Example #7
Source File: recast.py From cloudformation-cli-python-plugin with Apache License 2.0 | 5 votes |
def get_forward_ref_type() -> Any: # ignoring mypy on the import as it catches (_)ForwardRef as invalid, use for # introspection is valid: # https://docs.python.org/3/library/typing.html#typing.ForwardRef if "ForwardRef" in dir(typing): return typing.ForwardRef # type: ignore return typing._ForwardRef # type: ignore
Example #8
Source File: _compat.py From punq with MIT License | 5 votes |
def ensure_forward_ref(self, service, factory, instance, **kwargs): if isinstance(service, str): self.register(ForwardRef(service), factory, instance, **kwargs)
Example #9
Source File: typing.py From pydantic with MIT License | 5 votes |
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: return type_._eval_type(globalns, localns)
Example #10
Source File: typing.py From pydantic with MIT License | 5 votes |
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: return type_._evaluate(globalns, localns)
Example #11
Source File: typing.py From pydantic with MIT License | 5 votes |
def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None: """ Try to update ForwardRefs on fields based on this ModelField, globalns and localns. """ if field.type_.__class__ == ForwardRef: field.type_ = evaluate_forwardref(field.type_, globalns, localns or None) field.prepare() if field.sub_fields: for sub_f in field.sub_fields: update_field_forward_refs(sub_f, globalns=globalns, localns=localns)
Example #12
Source File: type_util.py From pytypes with Apache License 2.0 | 4 votes |
def resolve_fw_decl(in_type, module_name=None, globs=None, level=0, search_stack_depth=2): '''Resolves forward references in ``in_type``, see https://www.python.org/dev/peps/pep-0484/#forward-references. Note: ``globs`` should be a dictionary containing values for the names that must be resolved in ``in_type``. If ``globs`` is not provided, it will be created by ``__globals__`` from the module named ``module_name``, plus ``__locals__`` from the last ``search_stack_depth`` stack frames (Default: 2), beginning at the calling function. This is to resolve cases where ``in_type`` and/or types it fw-references are defined inside a function. To prevent walking the stack, set ``search_stack_depth=0``. Ideally provide a proper ``globs`` for best efficiency. See ``util.get_function_perspective_globals`` for obtaining a ``globs`` that can be cached. ``util.get_function_perspective_globals`` works like described above. ''' # Also see discussion at https://github.com/Stewori/pytypes/pull/43 if in_type in _fw_resolve_cache: return _fw_resolve_cache[in_type], True if globs is None: #if not module_name is None: globs = util.get_function_perspective_globals(module_name, level+1, level+1+search_stack_depth) if isinstance(in_type, _basestring): # For the case that a pure forward ref is given as string out_type = eval(in_type, globs) _fw_resolve_cache[in_type] = out_type return out_type, True elif isinstance(in_type, ForwardRef): # Todo: Mabe somehow get globs from in_type.__forward_code__ if not in_type.__forward_evaluated__: in_type.__forward_value__ = eval(in_type.__forward_arg__, globs) in_type.__forward_evaluated__ = True return in_type, True elif is_Tuple(in_type): return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \ for in_tp in get_Tuple_params(in_type)]) elif is_Union(in_type): return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \ for in_tp in get_Union_params(in_type)]) elif is_Callable(in_type): args, res = get_Callable_args_res(in_type) ret = any([resolve_fw_decl(in_tp, None, globs)[1] \ for in_tp in args]) ret = resolve_fw_decl(res, None, globs)[1] or ret return in_type, ret elif hasattr(in_type, '__args__') and in_type.__args__ is not None: return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \ for in_tp in in_type.__args__]) return in_type, False