本文整理匯總了Python中__future__.annotations方法的典型用法代碼示例。如果您正苦於以下問題:Python __future__.annotations方法的具體用法?Python __future__.annotations怎麽用?Python __future__.annotations使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類__future__
的用法示例。
在下文中一共展示了__future__.annotations方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_postponed_annotations
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def test_postponed_annotations(self):
self.flakes('''
from __future__ import annotations
def f(a: A) -> A: pass
class A:
b: B
class B: pass
''')
self.flakes('''
from __future__ import annotations
def f(a: A) -> A: pass
class A:
b: Undefined
class B: pass
''', m.UndefinedName)
示例2: using_future_annotations
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def using_future_annotations(node: nc.NodeNG) -> nc.NodeNG:
"""Return whether postponed annotation evaluation is enabled (PEP 563)."""
# Find the module.
mnode = node
while mnode.parent is not None:
mnode = mnode.parent
# Look for 'from __future__ import annotations' to decide
# if we should assume all annotations are defer-eval'ed.
# NOTE: this will become default at some point within a few years..
annotations_set = mnode.locals.get('annotations')
if (annotations_set and isinstance(annotations_set[0], astroid.ImportFrom)
and annotations_set[0].modname == '__future__'):
return True
return False
示例3: add_annotation
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def add_annotation(self,
schema: s_schema.Schema,
annotation: AnnotationValue,
replace: bool = False) -> s_schema.Schema:
schema = self.add_classref(
schema, 'annotations', annotation, replace=replace)
return schema
示例4: del_annotation
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def del_annotation(self,
schema: s_schema.Schema,
annotation_name: str) -> s_schema.Schema:
shortname = sn.shortname_from_fullname(annotation_name)
return self.del_classref(schema, 'annotations', shortname)
示例5: test_get_migration_19
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def test_get_migration_19(self):
# Test abstract and concrete annotations order of declaration.
schema = r'''
type Foo {
property name -> str;
annotation my_anno := 'Foo';
}
abstract annotation my_anno;
'''
self._assert_migration_consistency(schema)
示例6: test_get_migration_20
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def test_get_migration_20(self):
# Test abstract and concrete annotations order of declaration.
schema = r'''
type Foo {
property name -> str {
annotation my_anno := 'Foo';
}
}
abstract annotation my_anno;
'''
self._assert_migration_consistency(schema)
示例7: annotations
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def annotations(self) -> Dict[str, str]:
return self.metadata.get('annotations', {})
示例8: ambassador_id
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def ambassador_id(self) -> str:
return self.annotations.get('getambassador.io/ambassador-id', 'default')
示例9: test_type_cast_literal_str_to_str
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def test_type_cast_literal_str_to_str(self):
# Checks that our handling of quoted type annotations in the first
# argument to `cast` doesn't cause issues when (only) the _second_
# argument is a literal str which looks a bit like a type annoation.
self.flakes("""
from typing import cast
a_string = cast(str, 'Optional[int]')
""")
示例10: test_partial_string_annotations_with_future_annotations
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def test_partial_string_annotations_with_future_annotations(self):
self.flakes("""
from __future__ import annotations
from queue import Queue
from typing import Optional
def f() -> Optional['Queue[str]']:
return None
""")
示例11: func_annotations_filter
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def func_annotations_filter(node: nc.NodeNG) -> nc.NodeNG:
"""Filter annotated function args/retvals.
This accounts for deferred evaluation available in in Python 3.7+
via 'from __future__ import annotations'. In this case we don't
want Pylint to complain about missing symbols in annotations when
they aren't actually needed at runtime.
"""
# Only do this if deferred annotations are on.
if not using_future_annotations(node):
return node
# Wipe out argument annotations.
# Special-case: functools.singledispatch and ba.dispatchmethod *do*
# evaluate annotations at runtime so we want to leave theirs intact.
# Lets just look for a @XXX.register decorator used by both I guess.
if node.decorators is not None:
for dnode in node.decorators.nodes:
if (isinstance(dnode, astroid.nodes.Name)
and dnode.name in ('dispatchmethod', 'singledispatch')):
return node # Leave annotations intact.
if (isinstance(dnode, astroid.nodes.Attribute)
and dnode.attrname == 'register'):
return node # Leave annotations intact.
node.args.annotations = [None for _ in node.args.args]
node.args.varargannotation = None
node.args.kwargannotation = None
node.args.kwonlyargs_annotations = [None for _ in node.args.kwonlyargs]
# Wipe out return-value annotation.
if node.returns is not None:
node.returns = None
return node
示例12: register_plugins
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def register_plugins(manager: astroid.Manager) -> None:
"""Apply our transforms to a given astroid manager object."""
# Hmm; is this still necessary?
if VERBOSE:
manager.register_failed_import_hook(failed_import_hook)
# Completely ignore everything under an 'if TYPE_CHECKING' conditional.
# That stuff only gets run for mypy, and in general we want to
# check code as if it doesn't exist at all.
manager.register_transform(astroid.If, ignore_type_check_filter)
# We use 'reveal_type()' quite often, which tells mypy to print
# the type of an expression. Let's ignore it in Pylint's eyes so
# we don't see an ugly error there.
manager.register_transform(astroid.Call, ignore_reveal_type_call)
# We make use of 'from __future__ import annotations' which causes Python
# to receive annotations as strings, and also 'if TYPE_CHECKING:' blocks,
# which lets us do imports and whatnot that are limited to type-checking.
# Let's make Pylint understand these.
manager.register_transform(astroid.AnnAssign, var_annotations_filter)
manager.register_transform(astroid.FunctionDef, func_annotations_filter)
manager.register_transform(astroid.AsyncFunctionDef,
func_annotations_filter)
# Pylint doesn't seem to support Generics much right now, and it seems
# to lead to some buggy behavior and slowdowns. So let's filter them
# out. So instead of this:
# class MyClass(MyType[T]):
# Pylint will see this:
# class MyClass(MyType):
# I've opened a github issue related to the problems I was hitting,
# so we can revisit the need for this if that gets resolved.
# https://github.com/PyCQA/pylint/issues/3605
manager.register_transform(astroid.ClassDef, class_generics_filter)
示例13: main
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def main(*, stdout: bool):
import edb
for p in edb.__path__:
ep = pathlib.Path(p) / 'api' / 'types.txt'
if ep.exists():
out_fn = pathlib.Path(p) / 'schema' / '_types.py'
break
else:
die('Unable to find the "edb/api/types.txt" file')
items_code = []
with open(ep, 'rt') as f:
for line in f.readlines():
if re.match(r'(?x)^ (\s*\#[^\n]*) | (\s*) $', line):
continue
parts = re.split(r'\s+', line.strip())
tid, name = parts
items_code.append(f' {name!r}: {uuid.UUID(tid)!r},')
code = (
f'# AUTOGENERATED FROM "edb/api/types.txt" WITH\n'
f'# $ edb gen-types'
f'\n\n\n'
f'from __future__ import annotations'
f'\n'
f'from typing import * # NoQA'
f'\n\n\n'
f'import uuid'
f'\n\n'
f'from edb.common import uuidgen'
f'\n\n\n'
f'UUID: Type[uuid.UUID] = uuidgen.UUID'
f'\n\n\n'
f'TYPE_IDS = {{'
f'\n' +
"\n".join(items_code) +
f'\n'
f'}}'
f'\n'
)
if stdout:
print(code, end='')
else:
with open(out_fn, 'wt') as f:
f.write(code)
示例14: _dataclass_validate
# 需要導入模塊: import __future__ [as 別名]
# 或者: from __future__ import annotations [as 別名]
def _dataclass_validate(instance: Any, values: Dict[str, Any]) -> None:
# pylint: disable=too-many-branches
if not dataclasses.is_dataclass(instance):
raise TypeError(f'Passed instance {instance} is not a dataclass.')
if not isinstance(values, dict):
raise TypeError("Expected a dict for 'values' arg.")
fields = dataclasses.fields(instance)
fieldsdict = {f.name: f for f in fields}
for key, value in values.items():
if key not in fieldsdict:
raise AttributeError(
f"'{type(instance).__name__}' has no '{key}' field.")
field = fieldsdict[key]
# We expect to be operating under 'from __future__ import annotations'
# so field types should always be strings for us; not an actual types.
# Complain if we come across an actual type.
fieldtype: str = field.type # type: ignore
if not isinstance(fieldtype, str):
raise RuntimeError(
f'Dataclass {type(instance).__name__} seems to have'
f' been created without "from __future__ import annotations";'
f' those dataclasses are unsupported here.')
if fieldtype in _SIMPLE_ASSIGN_TYPES:
reqtypes = _SIMPLE_ASSIGN_TYPES[fieldtype]
valuetype = type(value)
if not any(valuetype is t for t in reqtypes):
if len(reqtypes) == 1:
expected = reqtypes[0].__name__
else:
names = ', '.join(t.__name__ for t in reqtypes)
expected = f'Union[{names}]'
raise TypeError(f'Invalid value type for "{key}";'
f' expected "{expected}", got'
f' "{valuetype.__name__}".')
elif fieldtype in _LIST_ASSIGN_TYPES:
reqtypes = _LIST_ASSIGN_TYPES[fieldtype]
if not isinstance(value, list):
raise TypeError(
f'Invalid value for "{key}";'
f' expected a list, got a "{type(value).__name__}"')
for subvalue in value:
subvaluetype = type(subvalue)
if not any(subvaluetype is t for t in reqtypes):
if len(reqtypes) == 1:
expected = reqtypes[0].__name__
else:
names = ', '.join(t.__name__ for t in reqtypes)
expected = f'Union[{names}]'
raise TypeError(f'Invalid value type for "{key}";'
f' expected list of "{expected}", found'
f' "{subvaluetype.__name__}".')
else:
raise TypeError(f'Field type "{fieldtype}" is unsupported here.')