def test_Type():
from typing import Type, Any
class A(object): pass
class B(A): pass
class C(B): pass
class D(A): pass
assert is_type(A, type)
assert is_type(A, Type)
assert is_type(A, Type[Any])
assert is_type(A, Type[object])
assert is_type(A, Type[A])
assert is_type(B, Type[A])
assert is_type(C, Type[A])
assert is_type(C, Type[B])
assert is_type(D, Type[A])
assert not is_type(A, Type[B])
assert not is_type(D, Type[B])
assert not is_type("str", Type)
assert not is_type(None, Type[A])
python类Type()的实例源码
def test_typing():
from typing import Any, List, Set, Dict, Type, Tuple
assert name_type(Any) == "Any"
assert name_type(List) == "List"
assert name_type(List[Any]) == "List"
assert name_type(List[str]) == "List[str]"
assert name_type(List[int]) == "List[int]"
assert name_type(Set) == "Set"
assert name_type(Set[Any]) == "Set"
assert name_type(Set[List]) == "Set[List]"
assert name_type(Dict) == "Dict"
assert name_type(Dict[Any, Any]) == "Dict"
assert name_type(Dict[str, int]) == "Dict[str, int]"
assert name_type(Type) == "Type"
assert name_type(Type[int]) == "Type[int]"
assert name_type(Type[MagicType]) == "Type[MagicType]"
assert name_type(Tuple) == "Tuple"
assert name_type(Tuple[int]) == "Tuple[int]"
assert name_type(Tuple[int, str, List]) == "Tuple[int, str, List]"
assert name_type(Tuple[int, Ellipsis]) == "Tuple[int, ...]"
assert name_type(Tuple[str, Ellipsis]) == "Tuple[str, ...]"
def create_master_instance(self, gen_cls, lib_name, params, used_cell_names, **kwargs):
# type: (Type[MasterType], str, Dict[str, Any], Set[str], **kwargs) -> MasterType
"""Create a new non-finalized master instance.
This instance is used to determine if we created this instance before.
Parameters
----------
gen_cls : Type[MasterType]
the generator Python class.
lib_name : str
generated instance library name.
params : Dict[str, Any]
instance parameters dictionary.
used_cell_names : Set[str]
a set of all used cell names.
**kwargs
optional arguments for the generator.
Returns
-------
master : MasterType
the non-finalized generated instance.
"""
raise NotImplementedError('not implemented')
def _import_class_from_str(class_str):
# type: (str) -> Type
"""Given a Python class string, convert it to the Python class.
Parameters
----------
class_str : str
a Python class string/
Returns
-------
py_class : class
a Python class.
"""
sections = class_str.split('.')
module_str = '.'.join(sections[:-1])
class_str = sections[-1]
modul = importlib.import_module(module_str)
return getattr(modul, class_str)
def make_user(self, user_data: dict, *,
user_klass: typing.Type[UserType] = User,
override_cache: bool = False) -> UserType:
"""
Creates a new user and caches it.
:param user_data: The user data to use to create.
:param user_klass: The type of user to create.
:param override_cache: Should the cache be overridden?
:return: A new :class`~.User` (hopefully).
"""
id = int(user_data.get("id", 0))
if id in self._users and not override_cache:
return self._users[id]
user = user_klass(self.client, **user_data)
self._users[user.id] = user
return user
def load_plugin(self, klass: typing.Type[Plugin], *args,
module: str = None):
"""
Loads a plugin.
.. note::
The client instance will automatically be provided to the Plugin's ``__init__``.
:param klass: The plugin class to load.
:param args: Any args to provide to the plugin.
:param module: The module name provided with this plugin. Only used interally.
"""
# get the name and create the plugin object
plugin_name = getattr(klass, "plugin_name", klass.__name__)
instance = klass(self.client, *args)
# call load, of course
await instance.load()
self.plugins[plugin_name] = instance
if module is not None:
self._module_plugins[module].append(instance)
return instance
def _warn(self, msg, category: Type[Warning]=RuntimeWarning):
if self._show_warnings:
warnings.warn(msg, category)
def from_dict(cls: Type[T], dikt) -> T:
"""
Returns the dict as a model
"""
return deserialize_model(dikt, cls)
def __init__(self,
username: str,
password: str,
botModule: str,
botconfig: Mapping,
*args,
**kwargs) -> None:
super().__init__(*args, **kwargs)
self.username: str = username
self.password: str = password
module = importlib.import_module(botModule + '.bot')
self.botCls: Type[Bot] = module.Bot # type: ignore
self.botconfig: Mapping = botconfig
self.conn: socketIO_client.SocketIO
self.game: Optional[Game] = None
def __copy__(self) -> 'CardKnowledge':
cls: Type[CardKnowledge] = self.__class__
result: CardKnowledge = cls.__new__(cls)
result.__dict__.update(self.__dict__)
result.cantBe = {c: self.cantBe[c][:] for c in self.bot.colors}
return result
def __init__(self,
connection: Any,
variant: Variant,
names: List[str],
botPosition: int,
botCls: Type['bot.Bot'],
**kwargs) -> None:
self.connection: Any = connection
self.variant: Variant = variant
self.numPlayers: int = len(names)
self.botPosition: int = botPosition
self.bot: bot.Bot
self.bot = botCls(self, botPosition, names[botPosition], **kwargs)
self.players: List[Player] = [self.bot.create_player(p, names[p])
for p in range(self.numPlayers)]
self.turnCount: int = -1
self.deckCount: int = -1
self.scoreCount: int = 0
self.clueCount: int = 8
self.strikeCount: int = 0
self.currentPlayer: int = -1
self.deck: Dict[int, Card] = {}
self.discards: List[int] = []
self.playedCards: Dict[Color, List[Card]]
self.playedCards = {c: [] for c in variant.pile_colors}
self.actionLog: List[str] = []
self._lastAction: Optional[Action] = None
self._cardMoved: Optional[int] = None
self._cardPosition: Optional[int] = None
self._striked: bool = False
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value:
Optional[Exception], traceback: Optional[TracebackType]) \
-> None:
"""Terminate the server and join the thread on exit."""
self.server.terminate()
self.server.join()
def __init__(self, lattice: Type, arguments: Dict[str, Any]):
"""Create a stack of elements of a lattice.
:param lattice: type of the lattice
"""
super().__init__()
self._stack = [lattice(**arguments)]
def unsupported(type: Type[T]) -> UnsupportedError:
return UnsupportedError("The type \"{type}\" is not supported by this DataSource!".format(type=type.__name__))
def provides(self): # type: Union[Iterable[Type[T]], Type[Any]]
"""The types of objects the data store provides."""
types = set()
any_dispatch = False
try:
types.update(getattr(self.__class__, "get")._provides)
any_dispatch = True
except AttributeError:
pass
try:
types.update(getattr(self.__class__, "get_many")._provides)
any_dispatch = True
except AttributeError:
pass
return types if any_dispatch else TYPE_WILDCARD
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Gets a query from the data source.
Args:
query: The query being requested.
context: The context for the extraction (mutable).
Returns:
The requested object.
"""
pass
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]:
"""Gets a query from the data source, which contains a request for multiple objects.
Args:
query: The query being requested (contains a request for multiple objects).
context: The context for the extraction (mutable).
Returns:
The requested objects.
"""
pass
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]:
try:
sources = self._sources[type]
except KeyError as error:
raise DataSource.unsupported(type) from error
for source in sources:
try:
return source.get_many(type, deepcopy(query), context)
except NotFoundError:
continue
raise NotFoundError()
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
try:
sources = self._sources[type]
except KeyError as error:
raise DataSource.unsupported(type) from error
for source in sources:
try:
return source.get(type, deepcopy(query), context)
except NotFoundError:
continue
raise NotFoundError()
def unsupported(type: Type[T]) -> UnsupportedError:
return UnsupportedError("The type \"{type}\" is not supported by this DataSink!".format(type=type.__name__))