本文整理汇总了Python中typing.TYPE_CHECKING属性的典型用法代码示例。如果您正苦于以下问题:Python typing.TYPE_CHECKING属性的具体用法?Python typing.TYPE_CHECKING怎么用?Python typing.TYPE_CHECKING使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在模块typing的用法示例。
在下文中一共展示了typing.TYPE_CHECKING属性的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_database
点赞 6
# 需要导入模块: 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,
示例2: test_mypy_compliance
点赞 6
# 需要导入模块: 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,
示例3: demo
点赞 6
# 需要导入模块: 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,
示例4: demo
点赞 6
# 需要导入模块: 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,
示例5: ignore_type_check_filter
点赞 6
# 需要导入模块: 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,
示例6: _setup_player_and_team_types
点赞 6
# 需要导入模块: 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,
示例7: test_type_hint_comments
点赞 6
# 需要导入模块: 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,
示例8: _parent
点赞 5
# 需要导入模块: 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,
示例9: setup
点赞 5
# 需要导入模块: 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,
示例10: load
点赞 5
# 需要导入模块: 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,
示例11: add_context
点赞 5
# 需要导入模块: 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,
示例12: from_resource
点赞 5
# 需要导入模块: 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,
示例13: test_idomiatic_typing_guards
点赞 5
# 需要导入模块: 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,
示例14: test_typing_guard_for_protocol
点赞 5
# 需要导入模块: 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,
示例15: __init__
点赞 5
# 需要导入模块: 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,
示例16: demo
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None: # <1>
book = BookDict( # <2>
isbn='0134757599',
title='Refactoring, 2e',
authors=['Martin Fowler', 'Kent Beck'],
pagecount=478
)
authors = book['authors'] # <3>
if TYPE_CHECKING: # <4>
reveal_type(authors) # <5>
authors = 'Bob' # <6>
book['weight'] = 4.2
del book['title']
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:15,
示例17: demo
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
import typing
pop = [1, 1, 2, 3, 3, 3, 3, 4]
m = mode(pop)
if typing.TYPE_CHECKING:
reveal_type(pop)
reveal_type(m)
print(pop)
print(repr(m), type(m))
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:11,
示例18: demo
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
import typing
pop = 'abracadabra'
m = mode(pop)
if typing.TYPE_CHECKING:
reveal_type(pop)
reveal_type(m)
print(pop)
print(m.upper(), type(m))
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:12,
示例19: demo
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
import typing
pop = 'abracadabra'
m = mode(pop)
if typing.TYPE_CHECKING:
reveal_type(pop)
reveal_type(m)
print(pop)
print(m.upper(), type(m))
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:11,
示例20: demo
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo() -> None:
from typing import List, Set, TYPE_CHECKING
pop = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 2)]
m = mode(pop)
if TYPE_CHECKING:
reveal_type(pop)
reveal_type(m)
print(pop)
print(repr(m), type(m))
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:11,
示例21: test_top_tuples
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_top_tuples() -> None:
fruit = 'mango pear apple kiwi banana'.split()
series: Iterator[Tuple[int, str]] = (
(len(s), s) for s in fruit)
length = 3
expected = [(6, 'banana'), (5, 'mango'), (5, 'apple')]
result = top(series, length)
if TYPE_CHECKING:
reveal_type(series)
reveal_type(expected)
reveal_type(result)
assert result == expected
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:14,
示例22: test_top_objects_error
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_top_objects_error() -> None:
series = [object() for _ in range(4)]
if TYPE_CHECKING:
reveal_type(series)
with pytest.raises(TypeError) as exc:
top(series, 3)
assert "'
# end::TOP_TEST[]
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:10,
示例23: demo_args_list_float
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_args_list_float() -> None:
args = [2.5, 3.5, 1.5]
expected = 3.5
result = my.max(*args)
print(args, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(expected)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:12,
示例24: demo_args_iter_str
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_args_iter_str() -> None:
args = iter('banana kiwi mango apple'.split())
expected = 'mango'
result = my.max(args)
print(args, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(expected)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:12,
示例25: demo_args_iter_not_comparable_with_key
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_args_iter_not_comparable_with_key() -> None:
args = [object(), object(), object()]
key = id
expected = max(args, key=id)
result = my.max(args, key=key)
print(args, key, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(key)
reveal_type(expected)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:14,
示例26: demo_empty_iterable_with_default
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_empty_iterable_with_default() -> None:
args: List[float] = []
default = None
expected = None
result = my.max(args, default=default)
print(args, default, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(default)
reveal_type(expected)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:14,
示例27: demo_different_key_return_type
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_different_key_return_type() -> None:
args = iter('banana kiwi mango apple'.split())
key = len
expected = 'banana'
result = my.max(args, key=key)
print(args, key, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(key)
reveal_type(expected)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:14,
示例28: demo_different_key_none
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def demo_different_key_none() -> None:
args = iter('banana kiwi mango apple'.split())
key = None
expected = 'mango'
result = my.max(args, key=key)
print(args, key, expected, result, sep='\n')
assert result == expected
if TYPE_CHECKING:
reveal_type(args)
reveal_type(key)
reveal_type(expected)
reveal_type(result)
###################################### intentional type errors
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:16,
示例29: test_double_str
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_double_str() -> None:
given = 'A'
result = double(given)
assert result == given * 2
if TYPE_CHECKING:
reveal_type(given)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:9,
示例30: test_double_fraction
点赞 5
# 需要导入模块: import typing [as 别名]
# 或者: from typing import TYPE_CHECKING [as 别名]
def test_double_fraction() -> None:
from fractions import Fraction
given = Fraction(2, 5)
result = double(given)
assert result == given * 2
if TYPE_CHECKING:
reveal_type(given)
reveal_type(result)
开发者ID:fluentpython,项目名称:example-code-2e,代码行数:10,
注:本文中的typing.TYPE_CHECKING属性示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。