Exemple #1
0
 def __init__(self, name, bases, d):
     ABCMeta.__init__(self, name, bases, d)
     required_attrs = {
         'STAGES': list,
         'STAGE_MODES': dict,
         'STEPS_PER_STAGE': dict,
         'INTER_STAGE_DEPENDENCIES': dict,
         'INTRA_STAGE_DEPENDENCIES': dict,
         '__type__': str
     }
     if '__abstract__' in vars(self):
         if getattr(self, '__abstract__'):
             return
     for attr_name, attr_type in required_attrs.iteritems():
         if not hasattr(self, attr_name):
             raise AttributeError(
                 'Class "%s" must implement attribute "%s".' %
                 (self.__name__, attr_name))
         attr_val = getattr(self, attr_name)
         if not isinstance(attr_val, attr_type):
             raise TypeError(
                 'Attribute "%s" of class "%s" must have type %s.' %
                 (attr_name, self.__name__, attr_type.__name__))
         # TODO: check intra_stage_dependencies inter_stage_dependencies
         # based on __dependencies__
     _workflow_register[getattr(self, '__type__')] = self
Exemple #2
0
    def __init__(cls, name, bases, dct):
        ABCMeta.__init__(cls, name, bases, dct)
        if name == 'EnumValue':
            return

        setattr(cls, '_is_cls_init', False)
        setattr(cls, '_impl', cls.impl())
        setattr(cls, '_allowed_values', set())
        setattr(cls, '_value2name', {})
        setattr(cls, '_name2value', {})

        values = cls.values()

        if isinstance(values, (set, list, tuple)):
            # do this for EnumValueStr specifically so that we don't have to
            # return something like {'foo': 'foo', 'bar': 'bar'}
            values = {k: k for k in values}

        for k, v in values.items():
            k = cls.get_normalized_key(k)
            if isinstance(v, cls._impl):
                cls._allowed_values.add(v)
                cls._name2value[k] = v
                cls._value2name[v] = k
                setattr(cls, k, v)

        cls._is_cls_init = True
Exemple #3
0
    def __init__(cls, name, bases, dictionary):  # @NoSelf
        if not name.endswith("Base"):
            assert ("kind" in dictionary), name
            kind = dictionary["kind"]

            assert type(kind) is str, name
            assert kind not in NodeCheckMetaClass.kinds, name

            NodeCheckMetaClass.kinds[kind] = cls
            NodeCheckMetaClass.kinds[name] = cls

            def convert(value):
                if value in ("AND", "OR", "NOT"):
                    return value
                else:
                    return value.title()

            kind_to_name_part = "".join([convert(x) for x in kind.split('_')])
            assert name.endswith(kind_to_name_part), \
              (name, kind_to_name_part)

            # Automatically add checker methods for everything to the common
            # base class
            checker_method = "is" + kind_to_name_part

            def checkKind(self):
                return self.kind == kind

            if not hasattr(NodeBase, checker_method):
                setattr(NodeBase, checker_method, checkKind)

        ABCMeta.__init__(cls, name, bases, dictionary)
Exemple #4
0
    def __init__(cls, name, bases, d):

        # Register this type of auth_sources, based on the module name
        # Avoid registering the BaseAuthentication itself

        AuthSourceRegistry.registry[_decorate_cls_name(d['__module__'])] = cls
        ABCMeta.__init__(cls, name, bases, d)
Exemple #5
0
 def __init__(self, name, bases, d):
     ABCMeta.__init__(self, name, bases, d)
     required_attrs = {
         'STAGES': list,
         'STAGE_MODES': dict,
         'STEPS_PER_STAGE': dict,
         'INTER_STAGE_DEPENDENCIES': dict,
         'INTRA_STAGE_DEPENDENCIES': dict,
         '__type__': str
     }
     if '__abstract__' in vars(self):
         if getattr(self, '__abstract__'):
             return
     for attr_name, attr_type in required_attrs.iteritems():
         if not hasattr(self, attr_name):
             raise AttributeError(
                 'Class "%s" must implement attribute "%s".' % (
                     self.__name__, attr_name
                 )
             )
         attr_val = getattr(self, attr_name)
         if not isinstance(attr_val, attr_type):
             raise TypeError(
                 'Attribute "%s" of class "%s" must have type %s.' % (
                     attr_name, self.__name__, attr_type.__name__
                 )
             )
         # TODO: check intra_stage_dependencies inter_stage_dependencies
         # based on __dependencies__
     _workflow_registry[getattr(self, '__type__')] = self
Exemple #6
0
    def __init__(cls, clsname, bases, clsdict):  # @UnusedVariable @NoSelf
        ABCMeta.__init__(cls, clsname, bases, clsdict)

        for k, f in clsdict.items():
            is_normal_function = isinstance(f, FunctionType)
            is_staticmethod = isinstance(f, staticmethod)
            is_classmethod = isinstance(f, classmethod)

            if not (is_normal_function or is_staticmethod or is_classmethod):
                # print('skipping %s:%s, %s' % (clsname, k, f))
                continue
            if k == '__init__':
                continue

            # this_function = '%s:%s()' % (clsname, k)  # @UnusedVariable
            # print('considering %s' % this_function)

            superclasses = cls.mro()[1:]
            for b in superclasses:
                if k in b.__dict__:
                    f0 = b.__dict__[k]
                    if is_function_or_static(f0):
                        if isinstance(f0, classmethod):
                            # print('found ancestor classmethod')
                            pass
                        elif isinstance(f0, staticmethod):
                            # print('found ancestor staticmethod')
                            pass
                        else:
                            assert isinstance(f0, FunctionType)
                            if '__contracts__' in f0.__dict__:
                                spec = f0.__contracts__
                                # msg = 'inherit contracts for %s:%s() from %s' % (clsname, k, b.__name__)
                                # print(msg)
                                # TODO: check that the contracts are a subtype
                                from contracts import ContractException
                                try:
                                    from .main import contracts_decorate
                                    f1 = contracts_decorate(f, **spec)
                                except ContractException as e:
                                    from .utils import indent
                                    msg = 'Error while applying ContractsMeta magic.\n'
                                    msg += '  subclass:  %s\n' % clsname
                                    msg += '      base:  %s\n' % b.__name__
                                    msg += '  function:  %s()\n' % k
                                    msg += 'Exception:\n'
                                    msg += indent(traceback.format_exc(e), '| ') + '\n'
                                    msg += '(most likely parameters names are different?)'
                                    raise ContractException(msg)
                                setattr(cls, k, f1)
                                break
                    else:
                        pass
                else:
                    # print(' X not found in %s' % b.__name__)
                    pass


            else:
                pass
Exemple #7
0
    def __init__(cls, clsname, bases, clsdict):  # @UnusedVariable @NoSelf
        ABCMeta.__init__(cls, clsname, bases, clsdict)

        for k, f in clsdict.items():
            is_normal_function = isinstance(f, FunctionType)
            is_staticmethod = isinstance(f, staticmethod)
            is_classmethod = isinstance(f, classmethod)

            if not (is_normal_function or is_staticmethod or is_classmethod):
                # print('skipping %s:%s, %s' % (clsname, k, f))
                continue
            if k == '__init__':
                continue

            # this_function = '%s:%s()' % (clsname, k)  # @UnusedVariable
            # print('considering %s' % this_function)

            superclasses = cls.mro()[1:]
            for b in superclasses:
                if k in b.__dict__:
                    f0 = b.__dict__[k]
                    if is_function_or_static(f0):
                        if isinstance(f0, classmethod):
                            # print('found ancestor classmethod')
                            pass
                        elif isinstance(f0, staticmethod):
                            # print('found ancestor staticmethod')
                            pass
                        else:
                            assert isinstance(f0, FunctionType)
                            if '__contracts__' in f0.__dict__:
                                spec = f0.__contracts__
                                # msg = 'inherit contracts for %s:%s() from %s' % (clsname, k, b.__name__)
                                # print(msg)
                                # TODO: check that the contracts are a subtype
                                from contracts import ContractException
                                try:
                                    from .main import contracts_decorate
                                    f1 = contracts_decorate(f, **spec)
                                except ContractException as e:
                                    from .utils import indent
                                    msg = 'Error while applying ContractsMeta magic.\n'
                                    msg += '  subclass:  %s\n' % clsname
                                    msg += '      base:  %s\n' % b.__name__
                                    msg += '  function:  %s()\n' % k
                                    msg += 'Exception:\n'
                                    msg += indent(traceback.format_exc(), '| ') + '\n'
                                    msg += '(most likely parameters names are different?)'
                                    raise ContractException(msg)
                                setattr(cls, k, f1)
                                break
                    else:
                        pass
                else:
                    # print(' X not found in %s' % b.__name__)
                    pass


            else:
                pass
Exemple #8
0
    def __init__(cls, name, bases, dictionary):  # @NoSelf

        if not name.endswith("Base"):
            if "kind" not in dictionary:
                raise NuitkaNodeDesignError(
                    name, "Must provide class variable 'kind'")

            kind = dictionary["kind"]

            assert type(kind) is str, name
            assert kind not in NodeCheckMetaClass.kinds, (name, kind)

            NodeCheckMetaClass.kinds[kind] = cls
            NodeCheckMetaClass.kinds[name] = cls

            kind_to_name_part = "".join([x.title() for x in kind.split("_")])
            assert name.endswith(kind_to_name_part), (name, kind_to_name_part)

            # Automatically add checker methods for everything to the common
            # base class
            checker_method = "is" + kind_to_name_part

            # TODO: How about making these two functions, one to statically
            # return True and False, and put one in the base class, and one
            # in the new class, would be slightly faster.
            def checkKind(self):
                return self.kind == kind

            # Add automatic checker methods to the node base class.
            from .NodeBases import NodeBase

            if not hasattr(NodeBase, checker_method):
                setattr(NodeBase, checker_method, checkKind)

        ABCMeta.__init__(cls, name, bases, dictionary)
Exemple #9
0
    def __init__(cls, name, bases, dct):
        # Init Abstract Base Class
        ABCMeta.__init__(cls, name, bases, dct)

        # Register with providers, if registration info is provided
        provider_key = getattr(cls, 'provider_key', None)
        if provider_key is not None:
            PROVIDERS[provider_key] = cls
Exemple #10
0
    def __init__(cls, name, bases, d):
        """
        This method is used to register the objects based on object type.
        """

        if d and 'object_type' in d:
            ObjectRegistry.registry[d['object_type']] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #11
0
    def __init__(cls, name, bases, d):

        # Register this type of module, based on the module name
        # Avoid registering the BaseDriver itself

        if name != 'BaseTestGenerator':
            TestsGeneratorRegistry.registry[d['__module__']] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #12
0
    def __init__(cls, name, bases, d):

        # Register this type of module, based on the module name
        # Avoid registering the BaseDriver itself

        if name != 'BaseTestGenerator':
            TestsGeneratorRegistry.registry[d['__module__']] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #13
0
 def __init__(cls, name, bases, attrs):
     """
     Metaclass in charge of the registering, inherits from ABCMeta
     because ArtifactStore is an abstract class too.
     """
     ABCMeta.__init__(cls, name, bases, attrs)
     # Don't register this base class
     if name != 'ArtifactStore':
         STORES[name] = cls
Exemple #14
0
    def __init__(cls, name, bases, d):

        # Register this type of driver, based on the module name
        # Avoid registering the BaseDriver itself

        if name != 'BaseDriver':
            DriverRegistry.registry[_decorate_cls_name(d['__module__'])] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #15
0
    def __init__(cls, name, bases, d):
        """
        This method is used to register the objects based on object type.
        """

        if d and 'object_type' in d:
            ObjectRegistry.registry[d['object_type']] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #16
0
    def __init__(cls, name, bases, d):

        # Register this type of driver, based on the module name
        # Avoid registering the BaseDriver itself

        if name != 'BaseDriver':
            DriverRegistry.registry[_decorate_cls_name(d['__module__'])] = cls

        ABCMeta.__init__(cls, name, bases, d)
Exemple #17
0
 def __init__(cls, name, bases, dct):  # @NoSelf
     ABCMeta.__init__(cls, name, bases, dct)
     method2dec = {
         'belongs': decorate_belongs,
     }
     if all_disabled():
         # print('Removing extra checks on Spaces')
         pass
     else:
         decorate_methods(cls, name, bases, dct, method2dec)
Exemple #18
0
 def __init__(cls, name, bases, dct):  # @NoSelf
     ABCMeta.__init__(cls, name, bases, dct)
     method2dec = {
         'belongs': decorate_belongs,
     }
     if all_disabled():
         # print('Removing extra checks on Spaces')
         pass
     else:
         decorate_methods(cls, name, bases, dct, method2dec)
Exemple #19
0
    def __init__(cls, name, bases, dct):
        ABCMeta.__init__(cls, name, bases, dct)

        if not hasattr(cls, '_protocols'):
            cls._protocols = {}

        registry_keys = getattr(cls, 'PROTOCOLS', []) or []
        if registry_keys:
            for key in registry_keys:
                if key in cls._protocols and cls.__name__ != cls._protocols[key].__name__:
                    logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".format(cls.__name__, key, cls._protocols[key].__name__))
                else:
                    cls._protocols[key] = cls
Exemple #20
0
    def __init__(cls, name, bases, dct):
        ABCMeta.__init__(cls, name, bases, dct)

        if not hasattr(cls, '_protocols'):
            cls._protocols = {}

        registry_keys = getattr(cls, 'PROTOCOLS', []) or []
        if registry_keys:
            for key in registry_keys:
                if key in cls._protocols and cls.__name__ != cls._protocols[key].__name__:
                    logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".format(cls.__name__, key, cls._protocols[key].__name__))
                else:
                    cls._protocols[key] = cls
Exemple #21
0
    def __init__(cls, clsname, bases, clsattrs):
        """
        Create a ``.__doc__`` property for every ``%magic``.

        To get the ``--help`` output when using ``%magic?`` in IPython
        """
        ABCMeta.__init__(cls, clsname, bases, clsattrs)
        zetup.meta.__init__(cls, clsname, bases, clsattrs)

        def __doc__(self):
            """Print the ``--help`` output of this ``%magic``."""
            self.creator.parse_args(['--help'])

        cls.__doc__ = property(__doc__)
Exemple #22
0
    def __init__(cls, name, bases, d):

        # Register this type of module, based on the module name
        # Avoid registering the BaseDriver itself

        if name != 'BaseTestGenerator' and name != 'BaseFeatureTest':
            # Store/append test classes in 'registry' if test modules has
            # multiple classes
            if d['__module__'] in TestsGeneratorRegistry.registry:
                TestsGeneratorRegistry.registry[d['__module__']].append(cls)
            else:
                TestsGeneratorRegistry.registry[d['__module__']] = [cls]

        ABCMeta.__init__(cls, name, bases, d)
Exemple #23
0
    def __init__(cls, name, bases, dct):
        ABCMeta.__init__(cls, name, bases, dct)

        # Register interface class for subclasses
        if not hasattr(cls, '__interface__'):
            cls.__interface__ = cls

        # Read configuration
        explicit_overrides = cls.__get_config(bases, dct,
                                              'INTERFACE_EXPLICIT_OVERRIDES')
        raise_on_violation = cls.__get_config(bases, dct,
                                              'INTERFACE_RAISE_ON_VIOLATION')
        skipped_names = cls.__get_config(bases, dct, 'INTERFACE_SKIPPED_NAMES')

        # Iterate over names in `dct` and check for conformance to interface
        for key, value in dct.items():

            # Skip any key in skipped_names
            if key in skipped_names:  # pragma: no cover
                continue

            # Identify the first instance of this key in the MRO, if it exists, and check conformance
            is_override = False
            for base in cls.__mro__[1:]:
                if base is object:
                    continue
                if key in base.__dict__:
                    is_override = True
                    cls.__verify_conformance(
                        key,
                        name,
                        value,
                        base.__name__,
                        base.__dict__[key],
                        explicit_overrides=explicit_overrides,
                        raise_on_violation=raise_on_violation)
                    break

            if not is_override:
                verify_not_overridden(key,
                                      name,
                                      value,
                                      raise_on_violation=raise_on_violation)

        # Update documentation
        cls.__update_docs(cls, name, bases, dct)

        # Call subclass registration hook
        cls.__register_implementation__()
Exemple #24
0
def __constructor(self, name, bases, kwargs):
    # Register this type of auth_sources, based on the module name
    # Avoid registering the BaseAuthentication itself
    cls = self.__class__
    entry = self._decorate_cls_name(name, kwargs)

    if cls._registry is None:
        cls._registry = dict()
    else:
        if entry in cls._registry:
            raise RuntimeError(
                ("{} class is already been registered with {} "
                 "(package: {})").format(entry, cls._name_, cls._package_))

    if cls._initialized is True:
        cls._registry[entry] = self
    cls._initialized = True

    ABCMeta.__init__(self, name, bases, kwargs)
Exemple #25
0
    def __init__(cls, name, bases, dictionary):  # @NoSelf

        if not name.endswith("Base"):
            assert ("kind" in dictionary), name
            kind = dictionary["kind"]

            assert type(kind) is str, name
            assert kind not in NodeCheckMetaClass.kinds, name

            NodeCheckMetaClass.kinds[kind] = cls
            NodeCheckMetaClass.kinds[name] = cls

            def convert(value):
                if value in ("AND", "OR", "NOT"):
                    return value
                else:
                    return value.title()

            kind_to_name_part = "".join(
                [convert(x) for x in kind.split('_')]
            )
            assert name.endswith(kind_to_name_part), \
              (name, kind_to_name_part)

            # Automatically add checker methods for everything to the common
            # base class
            checker_method = "is" + kind_to_name_part

            # TODO: How about making these two functions, one to statically
            # return True and False, and put one in the base class, and one
            # in the new class, would be slightly faster.
            def checkKind(self):
                return self.kind == kind

            # Add automatic checker methods to the node base class.
            from .NodeBases import NodeBase

            if not hasattr(NodeBase, checker_method):
                setattr(NodeBase, checker_method, checkKind)

        ABCMeta.__init__(cls, name, bases, dictionary)
Exemple #26
0
    def __init__(cls, name, bases, dictionary):  # @NoSelf

        if not name.endswith("Base"):
            assert "kind" in dictionary, name
            kind = dictionary["kind"]

            assert type(kind) is str, name
            assert kind not in NodeCheckMetaClass.kinds, name

            NodeCheckMetaClass.kinds[kind] = cls
            NodeCheckMetaClass.kinds[name] = cls

            def convert(value):
                if value in ("AND", "OR", "NOT"):
                    return value
                else:
                    return value.title()

            kind_to_name_part = "".join([convert(x) for x in kind.split("_")])
            assert name.endswith(kind_to_name_part), (name, kind_to_name_part)

            # Automatically add checker methods for everything to the common
            # base class
            checker_method = "is" + kind_to_name_part

            # TODO: How about making these two functions, one to statically
            # return True and False, and put one in the base class, and one
            # in the new class, would be slightly faster.
            def checkKind(self):
                return self.kind == kind

            # Add automatic checker methods to the node base class.
            from .NodeBases import NodeBase

            if not hasattr(NodeBase, checker_method):
                setattr(NodeBase, checker_method, checkKind)

        ABCMeta.__init__(cls, name, bases, dictionary)
 def __init__(self, *args, **kwargs):
     ABCMeta.__init__(self, *args)
Exemple #28
0
 def __init__(cls, name, bases, attrs):
     ABCMeta.__init__(cls, name, bases, attrs)
     cls.sample_until_n_accepted = wrap_sample(cls.sample_until_n_accepted)
Exemple #29
0
 def __init__(cls, class_name, bases, attrs):
     return ABCMeta.__init__(cls, class_name, bases, attrs)
Exemple #30
0
 def __init__(cls, name, bases, attrs):
     ABCMeta.__init__(cls, name, bases, attrs)
     cls.fit = wrap_fit(cls.fit)
     cls.pdf = wrap_pdf(cls.pdf)
     cls.rvs_single = wrap_rvs_single(cls.rvs_single)
Exemple #31
0
 def __init__(cls, name, bases, attrs):
     ABCMeta.__init__(cls, name, bases, attrs)
     # Don't register this base class
     if name != 'ArtifactSource':
         SOURCES[name] = cls
Exemple #32
0
 def __init__(cls, name, base, dct):
     Loggable.__init__(cls, name, base, dct)
     ABCMeta.__init__(cls, name, base, dct)
Exemple #33
0
 def __init__(self, name, bases, attributes):
     ABCMeta.__init__(self, name, bases, attributes)
     self.warnings = set()
Exemple #34
0
 def __init__(cls, name, bases, dict_):
     ABCMeta.__init__(cls, name, bases, dict_)
     cls.ravel = DictObject()
     cls.ravel.local = local()
     cls.ravel.local.is_bootstrapped = False
Exemple #35
0
    def __init__(cls, name, bases, dct):  # @NoSelf
        ABCMeta.__init__(cls, name, bases, dct)

        if all_disabled():
            pass
        else:
            #             print('Adding checks on Primitive %s: Switches.disable_all = %s' % (name, Switches.disable_all))
            from mcdp_dp.primitive import NotSolvableNeedsApprox
            from mcdp_dp.primitive import WrongUseOfUncertain

            if 'solve' in cls.__dict__:
                solve = cls.__dict__['solve']

                def solve2(self, f):
                    if all_disabled():
                        return solve(self, f)

                    F = self.get_fun_space()
                    try:
                        F.belongs(f)
                    except NotBelongs as e:
                        msg = "Function passed to solve() is not in function space."
                        raise_wrapped(NotBelongs,
                                      e,
                                      msg,
                                      F=F,
                                      f=f,
                                      dp=self.repr_long(),
                                      exc=sys.exc_info())

                    try:
                        res = solve(self, f)
                        return res
                    except NotBelongs as e:
                        raise_wrapped(NotBelongs,
                                      e,
                                      'Solve failed.',
                                      self=self,
                                      f=f,
                                      exc=sys.exc_info())
                    except NotImplementedError as e:
                        raise_wrapped(NotImplementedError,
                                      e,
                                      'Solve not implemented for class %s.' %
                                      name,
                                      exc=sys.exc_info())
                    except NotSolvableNeedsApprox:
                        raise
                    except WrongUseOfUncertain:
                        raise
                    except Exception as e:
                        raise_wrapped(Exception,
                                      e,
                                      'Solve failed',
                                      f=f,
                                      self=self,
                                      exc=sys.exc_info())

                setattr(cls, 'solve', solve2)

            if 'get_implementations_f_m' in cls.__dict__:
                get_implementations_f_r = cls.__dict__[
                    'get_implementations_f_r']

                def get_implementations_f_r2(self, f, r):
                    if all_disabled():
                        return get_implementations_f_r(self, f, r)

                    F = self.get_fun_space()
                    R = self.get_fun_space()
                    try:
                        F.belongs(f)
                    except NotBelongs as e:
                        msg = "Function passed to get_implementations_f_r() is not in function space."
                        raise_wrapped(NotBelongs,
                                      e,
                                      msg,
                                      F=F,
                                      f=f,
                                      dp=self.repr_long(),
                                      exc=sys.exc_info())
                    try:
                        R.belongs(r)
                    except NotBelongs as e:
                        msg = "Function passed to get_implementations_f_r() is not in R space."
                        raise_wrapped(NotBelongs,
                                      e,
                                      msg,
                                      R=R,
                                      r=r,
                                      dp=self.repr_long(),
                                      exc=sys.exc_info())

                    try:
                        res = get_implementations_f_r(self, f, r)
                    except NotBelongs as e:
                        raise_wrapped(NotBelongs,
                                      e,
                                      'Solve failed.',
                                      self=self,
                                      f=f,
                                      exc=sys.exc_info())
                    except NotImplementedError as e:
                        raise_wrapped(
                            NotImplementedError, e,
                            'Solve not implemented for class %s.' % name)
                    except NotSolvableNeedsApprox:
                        raise
                    except WrongUseOfUncertain:
                        raise
                    except Exception as e:
                        raise_wrapped(Exception,
                                      e,
                                      'Solve failed',
                                      f=f,
                                      self=self,
                                      exc=sys.exc_info())

                    M = self.get_imp_space()
                    try:
                        for m in res:
                            M.belongs(m)
                    except NotBelongs as e:
                        raise_wrapped(
                            NotBelongs,
                            e,
                            'Result of get_implementations_f_r not in M.',
                            self=self,
                            m=m,
                            M=M,
                            exc=sys.exc_info())

                    return res

                setattr(cls, 'get_implementations_f_r',
                        get_implementations_f_r2)
Exemple #36
0
 def __init__(cls, name, bases, attrs):
     warn('use hived.worker.BaseWorker instead', DeprecationWarning)
     ABCMeta.__init__(cls, name, bases, attrs)
Exemple #37
0
    def __init__(cls, name, bases, dct):  # @NoSelf
        ABCMeta.__init__(cls, name, bases, dct)

        if all_disabled():
            pass
        else:
#             print('Adding checks on Primitive %s: Switches.disable_all = %s' % (name, Switches.disable_all))
            from mcdp_dp.primitive import NotSolvableNeedsApprox
            from mcdp_dp.primitive import WrongUseOfUncertain

            if 'solve' in cls.__dict__:
                solve = cls.__dict__['solve']

                def solve2(self, f):
                    if all_disabled():
                        return solve(self, f)
                    
                    F = self.get_fun_space()
                    try:
                        F.belongs(f)
                    except NotBelongs as e:
                        msg = "Function passed to solve() is not in function space."
                        raise_wrapped(NotBelongs, e, msg,
                                      F=F, f=f, dp=self.repr_long(), exc=sys.exc_info())

                    try:
                        res = solve(self, f)
                        return res
                    except NotBelongs as e:
                        raise_wrapped(NotBelongs, e,
                            'Solve failed.', self=self, f=f, exc=sys.exc_info())
                    except NotImplementedError as e:
                        raise_wrapped(NotImplementedError, e,
                            'Solve not implemented for class %s.' % name, exc=sys.exc_info())
                    except NotSolvableNeedsApprox:
                        raise
                    except WrongUseOfUncertain:
                        raise
                    except Exception as e:
                        raise_wrapped(Exception, e,
                            'Solve failed', f=f, self=self, exc=sys.exc_info())

                setattr(cls, 'solve', solve2)

            if 'get_implementations_f_m' in cls.__dict__:
                get_implementations_f_r = cls.__dict__['get_implementations_f_r']

                def get_implementations_f_r2(self, f, r):
                    if all_disabled():
                        return get_implementations_f_r(self, f, r)
                    
                    
                    F = self.get_fun_space()
                    R = self.get_fun_space()
                    try:
                        F.belongs(f)
                    except NotBelongs as e:
                        msg = "Function passed to get_implementations_f_r() is not in function space."
                        raise_wrapped(NotBelongs, e, msg,
                                      F=F, f=f, dp=self.repr_long(), exc=sys.exc_info())
                    try:
                        R.belongs(r)
                    except NotBelongs as e:
                        msg = "Function passed to get_implementations_f_r() is not in R space."
                        raise_wrapped(NotBelongs, e, msg,
                                      R=R, r=r, dp=self.repr_long(), exc=sys.exc_info())

                    try:
                        res = get_implementations_f_r(self, f, r)
                    except NotBelongs as e:
                        raise_wrapped(NotBelongs, e,
                            'Solve failed.', self=self, f=f, exc=sys.exc_info())
                    except NotImplementedError as e:
                        raise_wrapped(NotImplementedError, e,
                            'Solve not implemented for class %s.' % name)
                    except NotSolvableNeedsApprox:
                        raise
                    except WrongUseOfUncertain:
                        raise
                    except Exception as e:
                        raise_wrapped(Exception, e,
                            'Solve failed', f=f, self=self, exc=sys.exc_info())
                        
                    M = self.get_imp_space()
                    try:
                        for m in res:
                            M.belongs(m)
                    except NotBelongs as e:
                        raise_wrapped(NotBelongs, e,
                                      'Result of get_implementations_f_r not in M.',
                                      self=self, m=m, M=M, exc=sys.exc_info())

                    return res

                setattr(cls, 'get_implementations_f_r', get_implementations_f_r2)