当前位置: 首页>>代码示例>>Python>>正文


Python __future__.annotations方法代码示例

本文整理汇总了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) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:18,代码来源:test_type_annotations.py

示例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 
开发者ID:efroemling,项目名称:ballistica,代码行数:18,代码来源:pylintplugins.py

示例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 
开发者ID:edgedb,项目名称:edgedb,代码行数:9,代码来源:annos.py

示例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) 
开发者ID:edgedb,项目名称:edgedb,代码行数:7,代码来源:annos.py

示例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) 
开发者ID:edgedb,项目名称:edgedb,代码行数:14,代码来源:test_schema.py

示例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) 
开发者ID:edgedb,项目名称:edgedb,代码行数:15,代码来源:test_schema.py

示例7: annotations

# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import annotations [as 别名]
def annotations(self) -> Dict[str, str]:
        return self.metadata.get('annotations', {}) 
开发者ID:datawire,项目名称:ambassador,代码行数:4,代码来源:k8sobject.py

示例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') 
开发者ID:datawire,项目名称:ambassador,代码行数:4,代码来源:k8sobject.py

示例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]')
        """) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:11,代码来源:test_type_annotations.py

示例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
        """) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:13,代码来源:test_type_annotations.py

示例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 
开发者ID:efroemling,项目名称:ballistica,代码行数:39,代码来源:pylintplugins.py

示例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) 
开发者ID:efroemling,项目名称:ballistica,代码行数:38,代码来源:pylintplugins.py

示例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) 
开发者ID:edgedb,项目名称:edgedb,代码行数:50,代码来源:gen_types.py

示例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.') 
开发者ID:efroemling,项目名称:ballistica,代码行数:59,代码来源:dataclasses.py


注:本文中的__future__.annotations方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。