Python __future__.annotations() Examples
The following are 14
code examples of __future__.annotations().
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
__future__
, or try the search function
.
Example #1
Source File: test_type_annotations.py From pyflakes with MIT License | 6 votes |
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)
Example #2
Source File: pylintplugins.py From ballistica with MIT License | 6 votes |
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
Example #3
Source File: annos.py From edgedb with Apache License 2.0 | 5 votes |
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
Example #4
Source File: annos.py From edgedb with Apache License 2.0 | 5 votes |
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)
Example #5
Source File: test_schema.py From edgedb with Apache License 2.0 | 5 votes |
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)
Example #6
Source File: test_schema.py From edgedb with Apache License 2.0 | 5 votes |
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)
Example #7
Source File: k8sobject.py From ambassador with Apache License 2.0 | 5 votes |
def annotations(self) -> Dict[str, str]: return self.metadata.get('annotations', {})
Example #8
Source File: k8sobject.py From ambassador with Apache License 2.0 | 5 votes |
def ambassador_id(self) -> str: return self.annotations.get('getambassador.io/ambassador-id', 'default')
Example #9
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
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]') """)
Example #10
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
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 """)
Example #11
Source File: pylintplugins.py From ballistica with MIT License | 5 votes |
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
Example #12
Source File: pylintplugins.py From ballistica with MIT License | 5 votes |
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)
Example #13
Source File: gen_types.py From edgedb with Apache License 2.0 | 4 votes |
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)
Example #14
Source File: dataclasses.py From ballistica with MIT License | 4 votes |
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.')