Ejemplo n.º 1
0
def is_issubclass_case(cls: type, clsinfo: type) -> bool:
    # Return whether subclass_of(cls, clsinfo) holds a case that can be handled
    # by the builtin issubclass.
    from typish.functions._is_from_typing import is_from_typing

    return (not is_from_typing(clsinfo) and isinstance(cls, type)
            and clsinfo is not type and '__subclasscheck__' in dir(clsinfo))
Ejemplo n.º 2
0
def _instance_of(obj: object, clsinfo: object, state: State = DEFAULT) -> bool:
    from typish.classes._literal import LiteralAlias, is_literal_type
    from typish.functions._subclass_of import subclass_of
    from typish.functions._get_type import get_type
    from typish.functions._is_from_typing import is_from_typing

    if not is_from_typing(clsinfo) and '__instancecheck__' in dir(clsinfo):
        return isinstance(obj, clsinfo)

    if is_literal_type(clsinfo):
        alias = LiteralAlias.from_literal(clsinfo)
        return isinstance(obj, alias)

    type_ = get_type(obj, use_union=True, state=state)
    return subclass_of(type_, clsinfo)
Ejemplo n.º 3
0
def get_origin(t: type) -> type:
    """
    Return the origin of the given (generic) type. For example, for
    ``t=List[str]``, the result would be ``list``.
    :param t: the type of which the origin is to be found.
    :return: the origin of ``t`` or ``t`` if it is not generic.
    """
    from typish.functions._get_simple_name import get_simple_name

    simple_name = get_simple_name(t)
    result = _type_per_alias.get(simple_name, None)
    if isclass(t) and not is_from_typing(t):
        result = t
    elif not result:
        result = getattr(typing, simple_name, t)
    return result
Ejemplo n.º 4
0
def get_alias(cls: T) -> typing.Optional[T]:
    """
    Return the alias from the ``typing`` module for ``cls``. For example, for
    ``cls=list``, the result would be ``typing.List``. If ``cls`` is
    parameterized (>=3.9), then a parameterized ``typing`` equivalent is
    returned. If no alias exists for ``cls``, then ``None`` is returned.
    If ``cls`` already is from ``typing`` it is returned as is.
    :param cls: the type for which the ``typing`` equivalent is to be found.
    :return: the alias from ``typing``.
    """
    if is_from_typing(cls):
        return cls
    alias = _alias_per_type.get(cls.__name__, None)
    if alias:
        args = getattr(cls, '__args__', tuple())
        if args:
            alias = alias[args]
    return alias