本文整理汇总了Python中typing.get_type_hints函数的典型用法代码示例。如果您正苦于以下问题:Python get_type_hints函数的具体用法?Python get_type_hints怎么用?Python get_type_hints使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_type_hints函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_generics_replacement
def test_generics_replacement(self):
"""
Most basic change. Confirm that generic parameters are actually swapped
out on child classes.
"""
Domain = hktyping.HKTypeVar('Domain')
Codomain = hktyping.HKTypeVar('Codomain')
class Functor(hktyping.HKGeneric[Domain, Codomain]):
def fmap_like(self, function: Domain) -> Codomain:
pass
class ListFunctor(Functor[AnyCategory, ListCategory]):
pass
listf = ListFunctor()
self.assertEqual(Functor.__parameters__, (Domain, Codomain))
self.assertEqual(ListFunctor.__parameters__, (AnyCategory, ListCategory))
self.assertEqual(listf.__parameters__, (AnyCategory, ListCategory))
#
# THIS IS BAD - AND I SHOULD FEEL BAD
# It looks like the replacement is occuring to the parent, which is terrible
#
self.assertNotEqual(
typing.get_type_hints(Functor.fmap_like),
{'function': Domain, 'return': Codomain})
# These are correct
self.assertEqual(
typing.get_type_hints(ListFunctor.fmap_like),
{'function': AnyCategory, 'return': ListCategory})
self.assertEqual(
typing.get_type_hints(listf.fmap_like),
{'function': AnyCategory, 'return': ListCategory})
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:33,代码来源:test.py
示例2: test_delayed_syntax_error
def test_delayed_syntax_error(self):
def foo(a: 'Node[T'):
pass
with self.assertRaises(SyntaxError):
get_type_hints(foo)
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py
示例3: test_basics
def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self,
left: 'Optional[Node[T]]',
right: 'Node[T]' = None,
stuff: int = None,
blah=None):
self.left = left
self.right = right
def add_left(self, node: Optional['Node[T]']):
self.add_both(node, None)
def add_right(self, node: 'Node[T]' = None):
self.add_both(None, node)
t = Node[int]
both_hints = get_type_hints(t.add_both, globals(), locals())
self.assertEqual(both_hints['left'], Optional[Node[T]])
self.assertEqual(both_hints['right'], Optional[Node[T]])
self.assertEqual(both_hints['left'], both_hints['right'])
self.assertEqual(both_hints['stuff'], Optional[int])
self.assertNotIn('blah', both_hints)
left_hints = get_type_hints(t.add_left, globals(), locals())
self.assertEqual(left_hints['node'], Optional[Node[T]])
right_hints = get_type_hints(t.add_right, globals(), locals())
self.assertEqual(right_hints['node'], Optional[Node[T]])
开发者ID:ChaiYuanUMN,项目名称:mypy,代码行数:35,代码来源:test_typing.py
示例4: test_type_error
def test_type_error(self):
def foo(a: Tuple['42']):
pass
with self.assertRaises(TypeError):
get_type_hints(foo)
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py
示例5: test_name_error
def test_name_error(self):
def foo(a: 'Noode[T]'):
pass
with self.assertRaises(NameError):
get_type_hints(foo, locals())
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py
示例6: test_basics
def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self,
left: 'Optional[Node[T]]',
right: 'Node[T]' = None,
stuff: int = None,
blah=None):
self.left = left
self.right = right
def add_left(self, node: Optional['Node[T]']):
self.add_both(node, None)
def add_right(self, node: 'Node[T]' = None):
self.add_both(None, node)
t = Node[int]
both_hints = get_type_hints(t.add_both, globals(), locals())
assert both_hints['left'] == both_hints['right'] == Optional[Node[T]]
assert both_hints['stuff'] == Optional[int]
assert 'blah' not in both_hints
left_hints = get_type_hints(t.add_left, globals(), locals())
assert left_hints['node'] == Optional[Node[T]]
right_hints = get_type_hints(t.add_right, globals(), locals())
assert right_hints['node'] == Optional[Node[T]]
开发者ID:Alkalit,项目名称:cpython,代码行数:33,代码来源:test_typing.py
示例7: test_basics
def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self, left: "Optional[Node[T]]", right: "Node[T]" = None, stuff: int = None, blah=None):
self.left = left
self.right = right
def add_left(self, node: Optional["Node[T]"]):
self.add_both(node, None)
def add_right(self, node: "Node[T]" = None):
self.add_both(None, node)
t = Node[int]
both_hints = get_type_hints(t.add_both, globals(), locals())
assert both_hints["left"] == both_hints["right"] == Optional[Node[T]]
assert both_hints["stuff"] == Optional[int]
assert "blah" not in both_hints
left_hints = get_type_hints(t.add_left, globals(), locals())
assert left_hints["node"] == Optional[Node[T]]
right_hints = get_type_hints(t.add_right, globals(), locals())
assert right_hints["node"] == Optional[Node[T]]
开发者ID:Martinpku,项目名称:typing,代码行数:27,代码来源:test_typing.py
示例8: test_basics
def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self, left: "Optional[Node[T]]", right: "Node[T]" = None, stuff: int = None, blah=None):
self.left = left
self.right = right
def add_left(self, node: Optional["Node[T]"]):
self.add_both(node, None)
def add_right(self, node: "Node[T]" = None):
self.add_both(None, node)
t = Node[int]
both_hints = get_type_hints(t.add_both, globals(), locals())
self.assertEqual(both_hints["left"], Optional[Node[T]])
self.assertEqual(both_hints["right"], Optional[Node[T]])
self.assertEqual(both_hints["left"], both_hints["right"])
self.assertEqual(both_hints["stuff"], Optional[int])
self.assertNotIn("blah", both_hints)
left_hints = get_type_hints(t.add_left, globals(), locals())
self.assertEqual(left_hints["node"], Optional[Node[T]])
right_hints = get_type_hints(t.add_right, globals(), locals())
self.assertEqual(right_hints["node"], Optional[Node[T]])
开发者ID:GSmurf,项目名称:typing,代码行数:29,代码来源:test_typing.py
示例9: test_standard_generics
def test_standard_generics(self):
Domain = typing.TypeVar('Domain')
Codomain = typing.TypeVar('Codomain')
class Functor(typing.Generic[Domain, Codomain]):
def fmap_like(self, function: Domain) -> Codomain:
pass
class ListFunctor(Functor[AnyCategory, ListCategory]):
pass
listf = ListFunctor()
self.assertEqual(Functor.__parameters__, (Domain, Codomain))
self.assertEqual(ListFunctor.__parameters__, (AnyCategory, ListCategory))
self.assertEqual(listf.__parameters__, (AnyCategory, ListCategory))
self.assertEqual(
typing.get_type_hints(Functor.fmap_like),
{'function': Domain, 'return': Codomain})
# This is bad behavior - the __annotations__ on methods on our child class & instances
# does not reflect the changes to __parameters__
# However, this is the default behavior of typing, so I'm testing for it
self.assertEqual(
typing.get_type_hints(ListFunctor.fmap_like),
{'function': Domain, 'return': Codomain})
self.assertEqual(
typing.get_type_hints(listf.fmap_like),
{'function': Domain, 'return': Codomain})
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:28,代码来源:test.py
示例10: test_no_type_check_class
def test_no_type_check_class(self):
@no_type_check
class C:
def foo(a: "whatevers") -> {}:
pass
cth = get_type_hints(C.foo)
self.assertEqual(cth, {})
ith = get_type_hints(C().foo)
self.assertEqual(ith, {})
开发者ID:GSmurf,项目名称:typing,代码行数:10,代码来源:test_typing.py
示例11: test_union_forward
def test_union_forward(self):
def foo(a: Union['T']):
pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Union[T]})
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py
示例12: _annotations_corrector
def _annotations_corrector(function, bases, parameters):
"""
"""
annotations = typing.get_type_hints(function)
accumulator = dict()
for key, value in annotations.items():
# If it is an unfilled typevar
if isinstance(value, typing.TypeVar):
# Find parent with generic version of this parameter
position = None
for parent in bases:
if value in getattr(parent, '__parameters__', []):
position = parent.__parameters__.index(value)
if position is None:
raise ValueError("Could not find position in __parameters__ of parent classes")
# If this is a structured reference, resolve it
if _is_structured_forward_ref(value):
base = parameters[position]
tinyns = {value._structured_forward_ref_name: parameters[position]}
# my_lambda = "lambda {0}: {1}".format(value._structured_forward_ref_name, value._structured_forward_ref_code)
concrete = eval(value._structured_forward_ref_code, tinyns)
else:
concrete = parameters[position]
accumulator[key] = concrete
else:
accumulator[key] = value
return accumulator
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:29,代码来源:higher_kinded.py
示例13: fields
def fields(self) -> Dict[str, _Field]:
def make_factory(value: object) -> Callable[[], Any]:
return lambda: value
if self._fields is None:
hints = typing.get_type_hints(self.type)
# This is gnarly. Sorry. For each field, store its default_factory if present; otherwise
# create a factory returning its default if present; otherwise None. Default parameter
# in the lambda is a ~~hack~~ to avoid messing up the variable binding.
fields: Dict[str, _Field] = {
field.name: _Field(
field.default_factory # type: ignore
if field.default_factory is not MISSING # type: ignore
else (
(make_factory(field.default))
if field.default is not MISSING
else None
),
hints[field.name],
)
for field in dataclasses.fields(self.type)
}
self._fields = fields
return self._fields
开发者ID:i80and,项目名称:flutter,代码行数:26,代码来源:__init__.py
示例14: generate_new_enforcer
def generate_new_enforcer(func, generic, parent_root, instance_of, settings):
"""
Private function for generating new Enforcer instances for the incoming function
"""
if parent_root is not None:
if type(parent_root) is not Validator:
raise TypeError('Parent validator must be a Validator')
if instance_of is not None:
if type(instance_of) is not GenericProxy:
raise TypeError('Instance of a generic must be derived from a valid Generic Proxy')
if generic:
hints = OrderedDict()
if instance_of:
func = instance_of
func_type = type(func)
has_origin = func.__origin__ is not None
# Collects generic's parameters - TypeVar-s specified on itself or on origin (if constrained)
if not func.__parameters__ and (not has_origin or not func.__origin__.__parameters__):
raise TypeError('User defined generic is invalid')
parameters = func.__parameters__ if func.__parameters__ else func.__origin__.__parameters__
# Maps parameter names to parameters, while preserving the order of their definition
for param in parameters:
hints[param.__name__] = EnhancedTypeVar(param.__name__, type_var=param)
# Verifies that constraints do not contradict generic's parameter definition
# and bounds parameters to constraints (if constrained)
bound = bool(func.__args__)
if bound:
for i, param in enumerate(hints.values()):
arg = func.__args__[i]
if is_type_of_type(arg, param):
param.__bound__ = arg
else:
raise TypeError('User defined generic does not accept provided constraints')
# NOTE:
# Signature in generics should always point to the original unconstrained generic
# This applies even to the instances of such Generics
if has_origin:
signature = func.__origin__
else:
signature = func.__wrapped__ if func_type is GenericProxy else func
validator = init_validator(hints, parent_root)
else:
bound = False
signature = inspect.signature(func)
hints = typing.get_type_hints(func)
validator = init_validator(hints, parent_root)
return Enforcer(validator, signature, hints, generic, bound, settings)
开发者ID:RussBaz,项目名称:enforce,代码行数:60,代码来源:enforcers.py
示例15: test_callable_with_ellipsis_forward
def test_callable_with_ellipsis_forward(self):
def foo(a: 'Callable[..., T]'):
pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[..., T]})
开发者ID:brettcannon,项目名称:typing,代码行数:7,代码来源:test_typing.py
示例16: wrap_fun
def wrap_fun(fun: T, injector: Injector) -> T:
if isinstance(fun, LocalProxy):
return fun # type: ignore
if ismethod(fun):
fun = instance_method_wrapper(fun)
# Important: this block needs to stay here so it's executed *before* the
# hasattr(fun, '__call__') block below - otherwise things may crash.
if hasattr(fun, '__bindings__'):
return wrap_function(fun, injector)
if hasattr(fun, '__call__') and not isinstance(fun, type):
try:
type_hints = get_type_hints(fun)
except (AttributeError, TypeError):
# Some callables aren't introspectable with get_type_hints,
# let's assume they don't have anything to inject. The exception
# types handled here are what I encountered so far.
# It used to be AttributeError, then https://github.com/python/typing/pull/314
# changed it to TypeError.
wrap_it = False
except NameError:
wrap_it = True
else:
type_hints.pop('return', None)
wrap_it = type_hints != {}
if wrap_it:
return wrap_fun(inject(fun), injector)
if hasattr(fun, 'view_class'):
return wrap_class_based_view(fun, injector)
return fun
开发者ID:alecthomas,项目名称:flask_injector,代码行数:34,代码来源:flask_injector.py
示例17: check_callable
def check_callable(callable_: typing.Callable, hint: type) -> bool:
"""Check argument type & return type of :class:`typing.Callable`. since it
raises check :class:`typing.Callable` using `isinstance`, so compare in
diffrent way
:param callable_: callable object given as a argument
:param hint: assumed type of given ``callable_``
"""
if not callable(callable_):
return type(callable_), False
if callable(callable_) and not hasattr(callable_, '__code__'):
return type(callable_), True
hints = typing.get_type_hints(callable_)
return_type = hints.pop('return', type(None))
signature = inspect.signature(callable_)
arg_types = tuple(
param.annotation
for _, param in signature.parameters.items()
)
correct = all({
any({
hint.__args__ is None,
hint.__args__ is Ellipsis,
hint.__args__ == arg_types,
}),
any({
hint.__result__ is None,
hint.__result__ in (typing.Any, return_type)
})
})
return typing.Callable[list(arg_types), return_type], correct
开发者ID:spoqa,项目名称:tsukkomi,代码行数:32,代码来源:typed.py
示例18: message
def message(cls: Type[T]) -> Type[T]:
"""
Returns the same class as was passed in, with additional dunder attributes needed for
serialization and deserialization.
"""
type_hints = get_type_hints(cls)
try:
# Used to list all fields and locate fields by field number.
cls.__protobuf_fields__: Dict[int, Field] = dict(
make_field(field_.metadata['number'], field_.name, type_hints[field_.name])
for field_ in dataclasses.fields(cls)
)
except KeyError as e:
# FIXME: catch `KeyError` in `make_field` and re-raise as `TypeError`.
raise TypeError(f'type is not serializable: {e}') from e
# noinspection PyUnresolvedReferences
Message.register(cls)
cls.serializer = MessageSerializer(cls)
cls.type_url = f'type.googleapis.com/{cls.__module__}.{cls.__name__}'
cls.validate = Message.validate
cls.dump = Message.dump
cls.dumps = Message.dumps
cls.merge_from = Message.merge_from
cls.load = classmethod(load)
cls.loads = classmethod(loads)
return cls
开发者ID:eigenein,项目名称:protobuf,代码行数:30,代码来源:dataclasses_.py
示例19: delgator
def delgator(pol_tr: PolTRSpec, method: typing.Callable):
"""
Helper function to delegate methods calls from PolTRSpec to
the methods of TimeResSpec.
Parameters
----------
pol_tr : PolTRSpec
method : method of TimeResSpec
The method to wrap. Uses function annotations to check if the
method returns a new TimeResSpec.
"""
name = method.__name__
hints = typing.get_type_hints(method)
if "return" in hints:
do_return = hints["return"] == TimeResSpec
else:
do_return = False
@functools.wraps(method)
def func(*args, **kwargs):
para = method(pol_tr.para, *args, **kwargs)
perp = method(pol_tr.perp, *args, **kwargs)
if do_return:
return PolTRSpec(para, perp)
func.__docs__ = method.__doc__
func.__name__ = name
return func
开发者ID:Tillsten,项目名称:skultrafast,代码行数:29,代码来源:dataset.py
示例20: polymorphic
def polymorphic(func):
global _registry
func_key = func.__module__ + '.' + func.__qualname__
parameters = signature(func).parameters
parameters_tuple = tuple(parameters.values())
if func_key not in _registry:
def dispatcher(*args, **kwargs):
return _call_func(func_key, args, kwargs)
dispatcher = update_dispatcher(dispatcher, func, assign=True)
signature_mapping = OrderedDict()
signature_mapping[parameters_tuple] = func
signature_mapping.dispatcher = dispatcher
_registry[func_key] = signature_mapping
return dispatcher
elif parameters_tuple not in _registry[func_key]:
_registry[func_key][parameters_tuple] = func
dispatcher = _registry[func_key].dispatcher
return update_dispatcher(dispatcher, func, assign=False)
else:
hints = get_type_hints(func)
sig_gen = (
'{}:{}'.format(p, hints[p]) if p in hints else p
for p in parameters
)
raise PolypieException(
"Function '{func}' with signature ({sig}) "
"already exists".format(func=func_key, sig=', '.join(sig_gen))
)
开发者ID:un-def,项目名称:polypie,代码行数:28,代码来源:polypie.py
注:本文中的typing.get_type_hints函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论