Esempio n. 1
0
def ismappingtype(obj: Type[ObjectT]) -> TypeGuard[Type[Mapping]]:
    """Test whether this annotation is a subtype of :py:class:`typing.Mapping`.

    Parameters
    ----------
    obj

    Examples
    --------

    >>> import typic
    >>> from typing import Mapping, Dict, DefaultDict, NewType
    >>> typic.ismappingtype(Mapping)
    True
    >>> typic.ismappingtype(Dict[str, str])
    True
    >>> typic.ismappingtype(DefaultDict)
    True
    >>> typic.ismappingtype(dict)
    True
    >>> class MyDict(dict): ...
    ...
    >>> typic.ismappingtype(MyDict)
    True
    >>> class MyMapping(Mapping): ...
    ...
    >>> typic.ismappingtype(MyMapping)
    True
    >>> typic.ismappingtype(NewType("Foo", dict))
    True
    """
    obj = util.origin(obj)
    return builtins.issubclass(
        obj, (dict, Record, sqlite3.Row)) or builtins.issubclass(obj, Mapping)
Esempio n. 2
0
def get_all_deficit_models():

    all_deficit_modules = []
    for loader, module_name, _ in pkgutil.walk_packages([os.path.dirname(deficit_models.__file__)]):

        _module = loader.find_module(module_name).load_module(module_name)
        for n in dir(_module):
            v = _module.__dict__[n]
            if inspect.isclass(v) and issubclass(v, DeficitModel) and \
                    v not in [DeficitModel, ConvectionDeficitModel] and not issubclass(v, RotorAvgModel):
                all_deficit_modules.append(v())
    return all_deficit_modules
Esempio n. 3
0
def issubclass(o: Type[Any], t: Union[Type, Tuple[Type, ...]]) -> bool:
    """A safer subclass check...

    Validates that `t` and/or `o` are not instances.

    Parameters
    ----------
    o
        The type to validate
    t
        The type(s) to validate against

    Notes
    -----
    Not compatible with classes from :py:mod:`typing`, as they return False with
    :py:func:`inspect.isclass`

    Examples
    --------
    >>> import typic
    >>> class MyStr(str): ...
    ...
    >>> typic.issubclass(MyStr, str)
    True
    >>> typic.issubclass(MyStr(), str)
    False
    >>> typic.issubclass(MyStr, str())
    False
    """
    return _type_check(t) and _type_check(o) and builtins.issubclass(o, t)
Esempio n. 4
0
def issubclass(sub: Type, super: Union[Type, Tuple[Type, ...]]) -> bool:
    """
    Alternative issubclass implementation that interpretes instances of NewType for the first argument as their super type.
    """
    if typing_inspect.is_new_type(sub):
        return issubclass(sub.__supertype__, super)
    return builtins.issubclass(sub, super)
Esempio n. 5
0
 def setupConfigOptions(cls, **kwargs):
     default_opt_level = list(cls.defaultOptimizationLevel)
     assert issubclass(cls, SimpleProject)
     super().setupConfigOptions(**kwargs)
     cls.useMxgot = cls.addBoolOption(
         "use-mxgot",
         help=
         "Compile with -mxgot flag (should not be needed when using lld)")
     cls.debugInfo = cls.addBoolOption("debug-info",
                                       help="build with debug info",
                                       default=True)
     cls.optimizationFlags = cls.addConfigOption("optimization-flags",
                                                 kind=list,
                                                 metavar="OPTIONS",
                                                 default=default_opt_level)
     cls.use_asan = cls.addBoolOption(
         "use-asan",
         default=False,
         help="Build with AddressSanitizer enabled")
     cls._linkage = cls.addConfigOption(
         "linkage",
         help="Build static or dynamic (default means for host=dynamic,"
         " CHERI/MIPS=<value of option --cross-compile-linkage>)",
         default=Linkage.DEFAULT,
         kind=Linkage)
Esempio n. 6
0
def iscollectiontype(obj: Type[ObjectT]) -> TypeGuard[Type[Collection]]:
    """Test whether this annotation is a subclass of :py:class:`typing.Collection`.

    Includes builtins.

    Parameters
    ----------
    obj

    Examples
    --------

    >>> import typic
    >>> from typing import Collection, Mapping, NewType
    >>> typic.iscollectiontype(Collection)
    True
    >>> typic.iscollectiontype(Mapping[str, str])
    True
    >>> typic.iscollectiontype(str)
    True
    >>> typic.iscollectiontype(list)
    True
    >>> typic.iscollectiontype(NewType("Foo", dict))
    True
    >>> typic.iscollectiontype(int)
    False
    """
    obj = util.origin(obj)
    return obj in _COLLECTIONS or builtins.issubclass(obj, Collection)
Esempio n. 7
0
def inherits_from(obj, a_class):
    """
    Checks if obj is subclass of a specified class
    :param obj: Object
    :param a_class: Class
    :return: True if is subclass, False otherwise
    """
    if issubclass(type(obj), a_class) and not type(obj) is a_class:
        return True
    else:
        return False
Esempio n. 8
0
def issubclass(obj, cls):    # pylint: disable=redefined-builtin
    """A sane implementation of issubclass.

    See http://bugs.python.org/issue10569

    Python bare issubclass must be protected by an isinstance test first since
    it can only work on types and raises when provided something which is not a
    type.

    Args:
      obj: Any object or class.
      cls: The class to check against.

    Returns:
      True if obj is a subclass of cls and False otherwise.
    """
    return isinstance(obj, type) and builtins.issubclass(obj, cls)
Esempio n. 9
0
    def getPAM(self):
        """
        Retrieve a reference to the Pluggable Authentication Module
        (PAM) configured for the application.

        The application looks up a PAM reference in the
        ``CARDS_AUTHENTICATOR`` Django setting. If that setting
        is absent, authenticator class ``LocalClientAuthenticator``
        from the `cards_web.connect` module is returned by default.
        Otherwise, the value must be a sequence of two elements: a
        fully qualified module name on the application's path, and
        the name of the authenticator class or function compliant
        with requirements of `connect.Authenticator`.

        Returns
        -------
        connect.Authenticator | callable
            a reference to the configured or default authenticator

        Notes
        -----
            Pluggable Authentication Modules used with this application
            **must** support synchronous authentication mode.
        """
        if not hasattr(settings, 'CARDS_AUTHENTICATOR'):
            return connect.local_client_authenticator
        ref = settings.CARDS_AUTHENTICATOR
        if not isinstance(ref, collections.Sequence) or \
             type(ref) is str:
            raise TypeError('CARDS_AUTHENTICATOR setting'
                            ' must be a non-string sequence, got: ' +
                            type(ref).__name__)
        try:
            module = importlib.import_module(ref[0])
            auth = getattr(module, ref[1])
            if issubclass(auth, connect.Authenticator):
                auth = auth(*ref[2:])
        except:
            raise ValueError('CARDS_AUTHENTICATOR setting is'
                             ' not valid: ' + repr(ref))
        if not callable(auth):
            raise TypeError('CARDS_AUTHENTICATOR setting'
                            ' must point to a class derived from'
                            ' `cards_web.connect.Authenticator` or'
                            ' a function, got: ' + repr(auth))
        return auth
Esempio n. 10
0
def issubclass(obj, cls):  # pylint: disable=redefined-builtin
    """A sane implementation of issubclass.

    See http://bugs.python.org/issue10569

    Python bare issubclass must be protected by an isinstance test first since
    it can only work on types and raises when provided something which is not a
    type.

    Args:
      obj: Any object or class.
      cls: The class to check against.

    Returns:
      True if obj is a subclass of cls and False otherwise.
    """
    return isinstance(obj, type) and builtins.issubclass(obj, cls)
Esempio n. 11
0
    def __init__(self, behavior: ESBehavior, ref: ESRef):
        self.enemy_skill_id = behavior.enemy_skill_id
        self.behavior = copy.deepcopy(behavior)
        self.condition = None  # type: Optional[ESCondition]
        self.extra_description = None

        if not issubclass(self.btype, ESLogic):
            if ref.enemy_ai > 0 or ref.enemy_rnd > 0:
                self.condition = ESCondition(ref.enemy_ai, ref.enemy_rnd,
                                             self.behavior.params)

        # This seems bad but I'm not sure how to improve
        # Start terrible badness
        if isinstance(self.behavior, ESFlagOperation):
            self.behavior.flag = ref.enemy_ai
            self.behavior.flag_bin = bin(ref.enemy_ai)

        if isinstance(self.behavior, ESSetCounter):
            self.behavior.counter = ref.enemy_ai if self.behavior.type == 25 else 1

        if isinstance(self.behavior, ESSetCounterIf):
            self.behavior.counter_is = ref.enemy_ai
            self.behavior.counter = ref.enemy_rnd

        if isinstance(self.behavior, ESBranch):
            self.behavior.branch_value = ref.enemy_ai
            self.behavior.target_round = ref.enemy_rnd

        if self.btype in [ESRecoverEnemyAlly, ESAttackUPRemainingEnemies]:
            if self.condition:
                self.condition.enemies_remaining = self.behavior.enemy_count

        if self.btype in [ESSkillSetOnDeath, ESDeathCry]:
            self.condition = ESCondition(ref.enemy_ai, ref.enemy_rnd,
                                         self.behavior.params)
            if self.condition:
                self.condition.on_death = True

        if self.btype in [ESRandomSpawn]:
            if not self.condition:
                self.condition = ESCondition(ref.enemy_ai, ref.enemy_rnd,
                                             self.behavior.params)
            self.condition.condition_attributes = self.behavior.condition_attributes
Esempio n. 12
0
def istimedeltatype(obj: Type[ObjectT]) -> TypeGuard[Type[datetime.timedelta]]:
    """Test whether this annotation is a a date/datetime object.

    Parameters
    ----------
    obj

    Examples
    --------

    >>> import typic
    >>> import datetime
    >>> from typing import NewType
    >>> typic.istimedeltatype(datetime.timedelta)
    True
    >>> typic.istimedeltatype(NewType("Foo", datetime.timedelta))
    True
    """
    return builtins.issubclass(util.origin(obj), datetime.timedelta)
Esempio n. 13
0
def isdecimaltype(obj: Type[ObjectT]) -> TypeGuard[Type[decimal.Decimal]]:
    """Test whether this annotation is a Decimal object.

    Parameters
    ----------
    obj

    Examples
    --------

    >>> import typic
    >>> import decimal
    >>> from typing import NewType
    >>> typic.isdecimaltype(decimal.Decimal)
    True
    >>> typic.isdecimaltype(NewType("Foo", decimal.Decimal))
    True
    """
    return builtins.issubclass(util.origin(obj), decimal.Decimal)
Esempio n. 14
0
def isuuidtype(obj: Type[ObjectT]) -> TypeGuard[Type[uuid.UUID]]:
    """Test whether this annotation is a a date/datetime object.

    Parameters
    ----------
    obj

    Examples
    --------

    >>> import typic
    >>> import uuid
    >>> from typing import NewType
    >>> typic.isuuidtype(uuid.UUID)
    True
    >>> class MyUUID(uuid.UUID): ...
    ...
    >>> typic.isuuidtype(MyUUID)
    True
    >>> typic.isuuidtype(NewType("Foo", uuid.UUID))
    True
    """
    return builtins.issubclass(util.origin(obj), uuid.UUID)
Esempio n. 15
0
    lambda *args, **kwargs: builtins.input(*args, **kwargs), builtins.input)
input._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.input)(*args, **kwargs),
    builtins.input)
int = functools.update_wrapper(
    lambda *args, **kwargs: builtins.int(*args, **kwargs), builtins.int)
int._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.int)(*args, **kwargs), builtins.int)
isinstance = functools.update_wrapper(
    lambda *args, **kwargs: builtins.isinstance(*args, **kwargs),
    builtins.isinstance)
isinstance._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.isinstance)(*args, **kwargs),
    builtins.isinstance)
issubclass = functools.update_wrapper(
    lambda *args, **kwargs: builtins.issubclass(*args, **kwargs),
    builtins.issubclass)
issubclass._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.issubclass)(*args, **kwargs),
    builtins.issubclass)
iter = functools.update_wrapper(
    lambda *args, **kwargs: builtins.iter(*args, **kwargs), builtins.iter)
iter._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.iter)(*args, **kwargs),
    builtins.iter)
len = functools.update_wrapper(
    lambda *args, **kwargs: builtins.len(*args, **kwargs), builtins.len)
len._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.len)(*args, **kwargs), builtins.len)
list = functools.update_wrapper(
    lambda *args, **kwargs: builtins.list(*args, **kwargs), builtins.list)
Esempio n. 16
0
 def match(self, obj):
     if isinstance(obj, type):
         if issubclass(obj, Module):
             return True
     return False
Esempio n. 17
0
def isiteratortype(obj: Type[ObjectT]) -> TypeGuard[Type[Iterator]]:
    obj = util.origin(obj)
    return builtins.issubclass(obj, Iterator)