本文整理匯總了Python中typing.Type方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Type方法的具體用法?Python typing.Type怎麽用?Python typing.Type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __get__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def __get__(self, instance: t.Any, owner: t.Type) -> t.Any:
if instance is None:
return self
container = get_di_container(instance)
if not container:
raise DIErrors.NO_CONTAINER_PROVIDED.with_params(
class_name=instance.__class__.__qualname__,
attribute=self.label
)
context = self.context.determine(instance)
try:
return context.get(container=container)
except ConfigError as e:
raise e.with_params(
class_name=instance.__class__.__qualname__,
attribute=self.label,
context=e.params.get('context'),
)
示例2: import_dotted_path
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def import_dotted_path(dotted_path: str) -> t.Type:
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImportError if the import failed.
Code taken from: django.utils.module_loading,import_string v 1.9
"""
try:
module_path, qual_name = dotted_path.rsplit(':', 1) \
if ':' in dotted_path else dotted_path.rsplit('.', 1)
except ValueError as e:
msg = "'%s' doesn't look like a module path" % dotted_path
raise ImportError(msg) from e
obj = import_module(module_path)
try:
for chunk in qual_name.split('.'):
obj = getattr(obj, chunk)
except AttributeError as e:
msg = "Module '%s' does not define a '%s' attribute/class" % (
module_path, qual_name)
raise ImportError(msg) from e
return obj
示例3: assert_eigengate_implements_consistent_protocols
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def assert_eigengate_implements_consistent_protocols(
eigen_gate_type: Type[cirq.EigenGate],
*,
exponents: Sequence[Union[sympy.Basic, float]] = (
0, 1, -1, 0.25, -0.5, 0.1, sympy.Symbol('s')),
global_shifts: Sequence[float] = (0, -0.5, 0.1),
qubit_count: Optional[int] = None,
ignoring_global_phase: bool=False,
setup_code: str = _setup_code,
global_vals: Optional[Dict[str, Any]] = None,
local_vals: Optional[Dict[str, Any]] = None) -> None:
"""Checks that an EigenGate subclass is internally consistent and has a
good __repr__."""
cirq.testing.assert_eigengate_implements_consistent_protocols(
eigen_gate_type,
exponents=exponents,
global_shifts=global_shifts,
qubit_count=qubit_count,
ignoring_global_phase=ignoring_global_phase,
setup_code=setup_code,
global_vals=global_vals,
local_vals=local_vals)
示例4: errorhandler
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to errors that originate in routes in this blueprint. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.register_error_handler(error, func)
return func
return decorator
示例5: app_errorhandler
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def app_errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the App.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to all errors. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.record_once(lambda state: state.app.register_error_handler(error, func))
return func
return decorator
示例6: register_error_handler
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:
"""Add an error handler function to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.register_error_handler`. An example usage,
.. code-block:: python
def not_found():
...
blueprint = Blueprint(__name__)
blueprint.register_error_handler(404, not_found)
"""
self.record_once(lambda state: state.app.register_error_handler(error, func, self.name))
示例7: dumps
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def dumps(object_: Any, app: Optional["Quart"] = None, **kwargs: Any) -> str:
json_encoder: Type[json.JSONEncoder] = JSONEncoder
if app is None and _app_ctx_stack.top is not None: # has_app_context requires a circular import
app = current_app._get_current_object()
if app is not None:
json_encoder = app.json_encoder
if _request_ctx_stack.top is not None: # has_request_context requires a circular import
blueprint = app.blueprints.get(request.blueprint)
if blueprint is not None and blueprint.json_encoder is not None:
json_encoder = blueprint.json_encoder
kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])
kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
kwargs.setdefault("sort_keys", True)
kwargs.setdefault("cls", json_encoder)
return json.dumps(object_, **kwargs)
示例8: from_name
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def from_name(name: str) -> Type['Base']:
if name == 'voc2007':
from dataset.voc2007 import VOC2007
return VOC2007
elif name == 'coco2017':
from dataset.coco2017 import COCO2017
return COCO2017
elif name == 'voc2007-cat-dog':
from dataset.voc2007_cat_dog import VOC2007CatDog
return VOC2007CatDog
elif name == 'coco2017-person':
from dataset.coco2017_person import COCO2017Person
return COCO2017Person
elif name == 'coco2017-car':
from dataset.coco2017_car import COCO2017Car
return COCO2017Car
elif name == 'coco2017-animal':
from dataset.coco2017_animal import COCO2017Animal
return COCO2017Animal
else:
raise ValueError
示例9: symbol
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
"""Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
Returns:
A `SymbolWildcard` that matches the *symbol_type*.
"""
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
return SymbolWildcard(name)
return SymbolWildcard(symbol_type, variable_name=name)
示例10: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def __init__(self, symbol_type: Type[Symbol]=Symbol, variable_name=None) -> None:
"""
Args:
symbol_type:
A subclass of `Symbol` to constrain what the wildcard matches.
If not specified, the wildcard will match any `Symbol`.
Raises:
TypeError: if *symbol_type* is not a subclass of `Symbol`.
"""
super().__init__(1, True, variable_name)
if not issubclass(symbol_type, Symbol):
raise TypeError("The type constraint must be a subclass of Symbol")
self.symbol_type = symbol_type
示例11: build_fanduel_single_game_importer
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def build_fanduel_single_game_importer(mvp=True, star=False, pro=False) -> Type[FanDuelCSVImporter]:
class FanDuelSingleGameCSVImporter(FanDuelCSVImporter): # pragma: nocover
def import_players(self):
players = super().import_players()
extra_players = []
for player in players:
if mvp:
mvp_player = deepcopy(player)
mvp_player.fppg *= 2
mvp_player.rank = PlayerRank.MVP
extra_players.append(mvp_player)
if star:
star_player = deepcopy(player)
star_player.fppg *= 1.5
star_player.rank = PlayerRank.STAR
extra_players.append(star_player)
if pro:
pro_player = deepcopy(player)
pro_player.fppg *= 1.2
pro_player.rank = PlayerRank.PRO
extra_players.append(pro_player)
players.extend(extra_players)
return players
return FanDuelSingleGameCSVImporter
示例12: get_file_by_path
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def get_file_by_path(
self, row_type: Type[DbRow], folder: Path, name: str
) -> DatabaseMedia:
"""
Search for a media item by filename, this applies to any of the
BaseMedia/DbRow derived class pairs
"""
query = "SELECT {0} FROM {1} WHERE Path = ?" " AND FileName = ?;".format(
row_type.columns, row_type.table
)
self.cur.execute(query, (str(folder), name))
record = self.cur.fetchone()
return row_type(record).to_media()
# functions for managing the SyncFiles Table ##############################
# todo this could be generic and support Albums and LocalFiles too
示例13: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def __init__(self,
model_spec, # type: typing.Type[T]
**kwargs):
# type: (...) -> T
if isinstance(model_spec, ModelMeta):
self._model_class = model_spec
self.model_name = self.model_class.__name__
elif isinstance(model_spec, string_type):
self._model_class = None
self.model_name = model_spec
else:
raise TypeError("ModelType: Expected a model, got an argument "
"of the type '{}'.".format(model_spec.__class__.__name__))
super(ModelType, self).__init__(**kwargs)
示例14: raises
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def raises(exc: ('typing.Union[' # pylint: disable=bad-docstring-quotes
' typing.Type[BaseException], '
' typing.Tuple[typing.Type[BaseException]]]'),
func: typing.Callable,
*args: typing.Any) -> bool:
"""Check if a function raises a given exception.
Args:
exc: A single exception or an iterable of exceptions.
func: A function to call.
*args: The arguments to pass to the function.
Returns:
True if the exception was raised, False otherwise.
"""
try:
func(*args)
except exc:
return True
else:
return False
示例15: inc
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Type [as 別名]
def inc(self, exception=None): # type: (Optional[Type[ParseError]]) -> bool
"""
Increments the parser if the end of the input has not been reached.
Returns whether or not it was able to advance.
"""
try:
self._idx, self._current = next(self._chars)
return True
except StopIteration:
self._idx = len(self)
self._current = self.EOF
if exception:
raise self.parse_error(exception)
return False