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


Python typing.TYPE_CHECKING属性代码示例

本文整理汇总了Python中typing.TYPE_CHECKING属性的典型用法代码示例。如果您正苦于以下问题:Python typing.TYPE_CHECKING属性的具体用法?Python typing.TYPE_CHECKING怎么用?Python typing.TYPE_CHECKING使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在typing的用法示例。


在下文中一共展示了typing.TYPE_CHECKING属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_database

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def get_database(request: web.Request) -> web.Response:
    instance_id = request.match_info.get("id", "")
    instance = PluginInstance.get(instance_id, None)
    if not instance:
        return resp.instance_not_found
    elif not instance.inst_db:
        return resp.plugin_has_no_database
    if TYPE_CHECKING:
        table: Table
        column: Column
    return web.json_response({
        table.name: {
            "columns": {
                column.name: {
                    "type": str(column.type),
                    "unique": column.unique or False,
                    "default": column.default,
                    "nullable": column.nullable,
                    "primary": column.primary_key,
                    "autoincrement": column.autoincrement,
                } for column in table.columns
            },
        } for table in instance.get_db_tables().values()
    }) 
开发者ID:maubot,项目名称:maubot,代码行数:26,代码来源:instance_database.py

示例2: demo

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
    NOT_BOOK_JSON = """
        {"title": "Andromeda Strain",
         "flavor": "pistachio",
         "authors": true}
    """
    not_book = from_json(NOT_BOOK_JSON)  # <1>
    if TYPE_CHECKING:  # <2>
        reveal_type(not_book)
        reveal_type(not_book['authors'])

    print(not_book)  # <3>
    print(not_book['flavor'])  # <4>

    xml = to_xml(not_book)  # <5>
    print(xml)  # <6> 
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:18,代码来源:demo_not_book.py

示例3: test_mypy_compliance

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_mypy_compliance():
    class EvenType:
        def __init__(self, num):
            assert num % 2 is 0
            self.num = num

    if typing.TYPE_CHECKING:
        EvenDagsterType = EvenType
    else:
        EvenDagsterType = PythonObjectDagsterType(EvenType)

    @solid
    def double_even(_, even_num: EvenDagsterType) -> EvenDagsterType:
        return EvenType(even_num.num * 2)

    assert execute_solid(double_even, input_values={'even_num': EvenType(2)}).success 
开发者ID:dagster-io,项目名称:dagster,代码行数:18,代码来源:test_type_guide.py

示例4: demo

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
    import typing
    p1 = tuple(range(10))
    s1 = sample(p1, 3)
    if typing.TYPE_CHECKING:
        reveal_type(p1)
        reveal_type(s1)
    print(p1)
    print(s1)
    p2 = 'The quick brown fox jumps over the lazy dog'
    s2 = sample(p2, 10)
    if typing.TYPE_CHECKING:
        reveal_type(p2)
        reveal_type(s2)
    print(p2)
    print(s2) 
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:18,代码来源:sample.py

示例5: ignore_type_check_filter

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def ignore_type_check_filter(node: nc.NodeNG) -> nc.NodeNG:
    """Ignore stuff under 'if TYPE_CHECKING:' block at module level."""

    # Look for a non-nested 'if TYPE_CHECKING:'
    if (isinstance(node.test, astroid.Name)
            and node.test.name == 'TYPE_CHECKING'
            and isinstance(node.parent, astroid.Module)):

        # Find the module node.
        mnode = node
        while mnode.parent is not None:
            mnode = mnode.parent

        # First off, remove any names that are getting defined
        # in this block from the module locals.
        for cnode in node.body:
            _strip_import(cnode, mnode)

        # Now replace the body with a simple 'pass'. This will
        # keep pylint from complaining about grouped imports/etc.
        passnode = astroid.Pass(parent=node,
                                lineno=node.lineno + 1,
                                col_offset=node.col_offset + 1)
        node.body = [passnode]
    return node 
开发者ID:efroemling,项目名称:ballistica,代码行数:27,代码来源:pylintplugins.py

示例6: _setup_player_and_team_types

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def _setup_player_and_team_types(self) -> None:
        """Pull player and team types from our typing.Generic params."""

        # TODO: There are proper calls for pulling these in Python 3.8;
        # should update this code when we adopt that.
        # NOTE: If we get Any as PlayerType or TeamType (generally due
        # to no generic params being passed) we automatically use the
        # base class types, but also warn the user since this will mean
        # less type safety for that class. (its better to pass the base
        # player/team types explicitly vs. having them be Any)
        if not TYPE_CHECKING:
            self._playertype = type(self).__orig_bases__[-1].__args__[0]
            if not isinstance(self._playertype, type):
                self._playertype = Player
                print(f'ERROR: {type(self)} was not passed a Player'
                      f' type argument; please explicitly pass ba.Player'
                      f' if you do not want to override it.')
            self._teamtype = type(self).__orig_bases__[-1].__args__[1]
            if not isinstance(self._teamtype, type):
                self._teamtype = Team
                print(f'ERROR: {type(self)} was not passed a Team'
                      f' type argument; please explicitly pass ba.Team'
                      f' if you do not want to override it.')
        assert issubclass(self._playertype, Player)
        assert issubclass(self._teamtype, Team) 
开发者ID:efroemling,项目名称:ballistica,代码行数:27,代码来源:_activity.py

示例7: test_type_hint_comments

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_type_hint_comments(v):
    v.scan(
        """\
import typing

if typing.TYPE_CHECKING:
    from typing import List, Text

def foo(foo_li):
    # type: (List[Text]) -> None
    for bar in foo_li:
        bar.xyz()
"""
    )

    check(v.unused_imports, ["List", "Text"]) 
开发者ID:jendrikseipp,项目名称:vulture,代码行数:18,代码来源:test_scavenging.py

示例8: _parent

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def _parent(self) -> typing.Optional['WebKitElement']:
        """Get the parent element of this element."""
        self._check_vanished()
        elem = typing.cast(typing.Optional[QWebElement],
                           self._elem.parent())
        if elem is None or elem.isNull():
            return None

        if typing.TYPE_CHECKING:
            # pylint: disable=used-before-assignment
            assert isinstance(self._tab, webkittab.WebKitTab)

        return WebKitElement(elem, tab=self._tab) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:15,代码来源:webkitelem.py

示例9: setup

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def setup(app):
    typing.TYPE_CHECKING = True
    app.add_stylesheet("instaloader.css")
    app.connect('autodoc-process-signature', sphinx_autodoc_typehints.process_signature)
    app.connect('autodoc-process-docstring', sphinx_autodoc_typehints.process_docstring) 
开发者ID:instaloader,项目名称:instaloader,代码行数:7,代码来源:conf.py

示例10: load

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def load(self) -> "Porcupine":
        """Load Porcupine object."""
        dist = importlib_metadata.distribution("pvporcupine")
        porcupine_paths = [
            f
            for f in cast(List[importlib_metadata.PackagePath], dist.files)
            if f.name == "porcupine.py"
        ]

        if not porcupine_paths:
            raise RuntimeError("Unable to find porcupine.py in pvporcupine package")

        porcupine_path = porcupine_paths[0].locate().parent
        lib_path = porcupine_path.parent.parent

        sys.path.append(str(porcupine_path))

        if not TYPE_CHECKING:
            # pylint: disable=import-outside-toplevel, import-error
            from porcupine import Porcupine

        return Porcupine(
            library_path=str(self._library_path(lib_path)),
            model_file_path=str(self._model_file_path(lib_path)),
            keyword_file_path=str(self._keyword_file_path(lib_path)),
            sensitivity=0.5,
        ) 
开发者ID:home-assistant,项目名称:ada,代码行数:29,代码来源:hotword.py

示例11: add_context

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def add_context(self, ctx: IRTLSContext) -> None:
        if TYPE_CHECKING:
            # This is needed because otherwise self.__setitem__ confuses things.
            handler: Callable[[str, str], None]

        if ctx.is_fallback:
            self.is_fallback = True

        for secretinfokey, handler, hkey in [
            ( 'cert_chain_file', self.update_cert_zero, 'certificate_chain' ),
            ( 'private_key_file', self.update_cert_zero, 'private_key' ),
            ( 'cacert_chain_file', self.update_validation, 'trusted_ca' ),
        ]:
            if secretinfokey in ctx['secret_info']:
                handler(hkey, ctx['secret_info'][secretinfokey])

        for ctxkey, handler, hkey in [
            ( 'alpn_protocols', self.update_alpn, 'alpn_protocols' ),
            ( 'cert_required', self.__setitem__, 'require_client_certificate' ),
            ( 'min_tls_version', self.update_tls_version, 'tls_minimum_protocol_version' ),
            ( 'max_tls_version', self.update_tls_version, 'tls_maximum_protocol_version' ),
            ( 'sni', self.__setitem__, 'sni' ),
        ]:
            value = ctx.get(ctxkey, None)

            if value is not None:
                handler(hkey, value)

        # This is a separate loop because self.update_tls_cipher is not the same type
        # as the other updaters: it takes a list of strings for the value, not a single
        # string. Getting mypy to be happy with that is _annoying_.

        for ctxkey, list_handler, hkey in [
            ( 'cipher_suites', self.update_tls_cipher, 'cipher_suites' ),
            ( 'ecdh_curves', self.update_tls_cipher, 'ecdh_curves' ),
        ]:
            value = ctx.get(ctxkey, None)

            if value is not None:
                list_handler(hkey, value) 
开发者ID:datawire,项目名称:ambassador,代码行数:42,代码来源:v2tls.py

示例12: from_resource

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def from_resource(cls: Type[R], other: R,
                      rkey: Optional[str]=None,
                      location: Optional[str]=None,
                      kind: Optional[str]=None,
                      serialization: Optional[str]=None,
                      name: Optional[str]=None,
                      namespace: Optional[str]=None,
                      metadata_labels: Optional[str] = None,
                      apiVersion: Optional[str]=None,
                      **kwargs) -> R:
        new_name = name or other.name
        new_apiVersion = apiVersion or other.apiVersion
        new_namespace = namespace or other.namespace
        new_metadata_labels = metadata_labels or other.get('metadata_labels', None)

        # mypy 0.730 is Just Flat Wrong here. It tries to be "more strict" about
        # super(), which is fine, but it also flags this particular super() call
        # as an error, even though Type[R] is necessarily a Resource type.
        #
        # Since it's complaining about "argument 2 for super is not an instance
        # of argument 1", we need to assert() isinstance here -- but of course,
        # cls is _not_ an instance at all, it's a class, so isinstance() will
        # fail at runtime. So we only do the assertion if TYPE_CHECKING. Grrrr.
        if TYPE_CHECKING:
            assert(isinstance(cls, Resource))

        return super().from_resource(other, rkey=rkey, location=location, kind=kind,
                                     name=new_name, apiVersion=new_apiVersion, namespace=new_namespace,
                                     metadata_labels=new_metadata_labels, serialization=serialization, **kwargs)

    # ACResource.INTERNAL is the magic ACResource we use to represent something created by
    # Ambassador's internals. 
开发者ID:datawire,项目名称:ambassador,代码行数:34,代码来源:acresource.py

示例13: test_idomiatic_typing_guards

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_idomiatic_typing_guards(self):
        # typing.TYPE_CHECKING: python3.5.3+
        self.flakes("""
            from typing import TYPE_CHECKING

            if TYPE_CHECKING:
                from t import T

            def f():  # type: () -> T
                pass
        """)
        # False: the old, more-compatible approach
        self.flakes("""
            if False:
                from t import T

            def f():  # type: () -> T
                pass
        """)
        # some choose to assign a constant and do it that way
        self.flakes("""
            MYPY = False

            if MYPY:
                from t import T

            def f():  # type: () -> T
                pass
        """) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:31,代码来源:test_type_annotations.py

示例14: test_typing_guard_for_protocol

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_typing_guard_for_protocol(self):
        self.flakes("""
            from typing import TYPE_CHECKING

            if TYPE_CHECKING:
                from typing import Protocol
            else:
                Protocol = object

            class C(Protocol):
                def f():  # type: () -> int
                    pass
        """) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:15,代码来源:test_type_annotations.py

示例15: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def __init__(self, **data):
        if "pk" in data:
            data[self.Mapping.pk_name] = data.pop("pk")

        if typing.TYPE_CHECKING:
            self.__values__: Dict[str, Any] = {}
            self.__fields_set__: "SetStr" = set()

        pk_only = data.pop("__pk_only__", False)
        values, fields_set, _ = pydantic.validate_model(
            self, data, raise_exc=not pk_only
        )

        object.__setattr__(self, "__values__", values)
        object.__setattr__(self, "__fields_set__", fields_set) 
开发者ID:awesometoolbox,项目名称:ormantic,代码行数:17,代码来源:models.py


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