コード例 #1
0
ファイル: metaclass.py プロジェクト: AndreaCensi/contracts
    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
コード例 #2
0
ファイル: dependencies.py プロジェクト: dvischi/TissueMAPS
 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
コード例 #3
0
ファイル: config.py プロジェクト: AtomLaw/Ally-Py
 def decorator(clazz):
     assert isclass(clazz), 'Invalid class %s' % clazz
 
     calls = []
     for name, function in clazz.__dict__.items():
         if isfunction(function):
             try: calls.append(function._ally_call)
             except AttributeError: raise DevelError('No call for method at:\n%s' % locationStack(function))
             del function._ally_call
 
     services = [typeFor(base) for base in clazz.__bases__]
     services = [typ.service for typ in services if isinstance(typ, TypeService)]
     names = {call.name for call in calls}
     for srv in services:
         assert isinstance(srv, Service)
         for name, call in srv.calls.items():
             assert isinstance(call, Call)
             if name not in names:
                 calls.append(processGenericCall(call, generic))
                 names.add(name)
 
     service = Service(calls)
     if type(clazz) != ABCMeta:
         attributes = dict(clazz.__dict__)
         attributes.pop('__dict__', None)  # Removing __dict__ since is a reference to the old class dictionary.
         attributes.pop('__weakref__', None)
         clazz = ABCMeta(clazz.__name__, clazz.__bases__, attributes)
     abstract = set(clazz.__abstractmethods__)
     abstract.update(service.calls)
     clazz.__abstractmethods__ = frozenset(abstract)
 
     clazz._ally_type = TypeService(clazz, service)
     # This specified the detected type for the model class by using 'typeFor'
     return clazz
コード例 #4
0
ファイル: command.py プロジェクト: datallysis/pgadmin4
    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)
コード例 #5
0
ファイル: registry.py プロジェクト: asheshv/pgadmin4
    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)
コード例 #6
0
ファイル: route.py プロジェクト: datallysis/pgadmin4
    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)
コード例 #7
0
ファイル: space_meta.py プロジェクト: AndreaCensi/mcdp
 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)
コード例 #8
0
ファイル: duct.py プロジェクト: djKooks/omniduct
    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
コード例 #9
0
ファイル: type.py プロジェクト: cristidomsa/Ally-Py
 def __instancecheck__(self, instance):
     '''
     @see: ABCMeta.__instancecheck__
     '''
     if ABCMeta.__instancecheck__(self, instance): return True
     if self is not TypeSupport: return False
     return isinstance(getattr(instance, '_ally_type', None), Type)
コード例 #10
0
ファイル: operator.py プロジェクト: ilastik/lazyflow
    def __call__(cls, *args, **kwargs):
        # type.__call__ calls instance.__init__ internally
        try:
            instance = ABCMeta.__call__(cls, *args, **kwargs)
        except Exception as e:
            # FIXME: What is the point of this long exception message?
            # Why can't we just let the exception propagate up the stack?
            # Is it because of some weird interaction between this metaclass and the Qt event loop?
            # ....probably
            err = "Could not create instance of '{}'\n".format(cls)
            err += "args   = {}\n".format(args)
            err += "kwargs = {}\n".format(kwargs)
            err += "The exception was:\n"
            err += str(e)
            err += "\nTraceback:\n"
            import traceback
            import sys
            import io

            if sys.version_info.major == 2:
                s = io.BytesIO()
            else:
                s = io.StringIO()
            traceback.print_exc(file=s)
            err += s.getvalue()
            raise RuntimeError(err)
        instance._after_init()
        return instance
コード例 #11
0
 def __instancecheck__(cls, instance):
     if _has_concrete_method(cls, "__instancecheck__"):
         return cls.__instancecheck__(instance)
     else:
         # If __instancheck__ NOT redefined
         #   OR if it is redefined, but as an abstractmethod
         return ABCMeta.__instancecheck__(cls, instance)
コード例 #12
0
 def __new__(meta, classname, bases, classDict):
     """
     Create new class and copy all docstrings from base classes.
     """
     cls = ABCMeta.__new__(meta, classname, bases, classDict)
     for name in classDict:
         fn = classDict[name]
         if type(fn) != FunctionType:
             continue
         docs = []
         for base in cls.mro():
             if not hasattr(base, name) or base is object:
                 continue
             basefn = getattr(base, name)
             basedoc = getdoc(basefn)
             if basedoc:
                 docs.append((base, basedoc))
         if len(docs) == 0:
             doc = None
         elif len(docs) == 1:
             doc = docs[0][1]
         else:
             doc = ""
             if docs[0][0] is cls:
                 doc += docs[0][1]
                 docs = docs[1:]
             for d in docs:
                 doc += "\n\nOverrides %s.%s" % (d[0].__name__, name)
                 doc += d[1]
             doc = doc.lstrip('\n')
         cls.__dict__[name].__doc__ = doc
     return cls
コード例 #13
0
ファイル: bits.py プロジェクト: spadic/spadic10-software
    def __new__(mcls, name, bases, namespace):
        def find_field_spec(namespace, bases):
            """Look for a _fields attribute in the namespace or one of the base
            classes.
            """
            field_spec = namespace.get('_fields')
            for base in bases:
                if field_spec is not None:
                    break
                field_spec = getattr(base, '_fields', None)
            return field_spec

        def insert_namedtuple(name, bases, namespace):
            """Insert a namedtuple based on the given fields *after* the other
            base classes, so that calls to its methods can be intercepted.
            """
            field_names = list(namespace['_fields'])
            basetuple = namedtuple('{}Fields'.format(name), field_names)
            del basetuple._source  # is no longer accurate
            bases = bases + (basetuple,)
            namespace.setdefault('__doc__', basetuple.__doc__)
            namespace.setdefault('__slots__', ())
            return bases

        field_spec = find_field_spec(namespace, bases)
        if not isinstance(field_spec, abstractproperty):
            try:
                namespace['_fields'] = OrderedDict(field_spec)
            except ValueError:
                namespace['_fields'] = OrderedDict(parse_fields(field_spec))
            bases = insert_namedtuple(name, bases, namespace)
        return ABCMeta.__new__(mcls, name, bases, namespace)
コード例 #14
0
ファイル: mapper.py プロジェクト: gizm0bill/Ally-Py
 def __instancecheck__(self, instance):
     '''
     @see: ABCMeta.__instancecheck__
     '''
     if ABCMeta.__instancecheck__(self, instance): return True
     if self is not MappedSupport: return False
     return isinstance(getattr(instance, '__mapper__', None), Mapper)
コード例 #15
0
    def __new__(cls, cls_name, cls_parents, cls_dict):
        src_cls = ABCMeta.__new__(cls, cls_name, cls_parents, cls_dict)

        if cls_name.split('.')[-1] == 'NewBase':
            return src_cls

        is_abc = cls_dict.pop('__abstract__', False)

        set_abstract(src_cls, is_abc)

        cls_attr_names = [nm for nm in dir(src_cls) if not nm.startswith('__')]

        cls_dict = dict([(name, getattr(src_cls, name)) for name in cls_attr_names])

        if not is_abstract(src_cls):
            cls.validate(src_cls)
            source_attrs_dict = {}

            for name, attr in cls_dict.items():
                if isinstance(attr, AbstractAttr):
                    source_attrs_dict[name] = attr

            src_cls.__attrs__ = source_attrs_dict

        source_name = cls_dict.get('__sourcename__') or cls.get_source_name(src_cls)
        src_cls.__sourcename__ = source_name

        return src_cls
コード例 #16
0
 def instance(mcls):
     try:
         return mcls.__instance
     except AttributeError:
         cls = ABCMeta.__new__(mcls, 'namedtuple', (tuple,), {})
         mcls.__instance = cls
         return cls
コード例 #17
0
    def __new__(cls, name, bases, attrs):
        # type: (Type[ManifestItemMeta], str, Tuple[ManifestItemMeta, ...], Dict[str, Any]) -> type
        rv = ABCMeta.__new__(cls, name, bases, attrs)
        if not isabstract(rv):
            assert issubclass(rv, ManifestItem)
            assert isinstance(rv.item_type, str)
            item_types[rv.item_type] = rv

        return rv
コード例 #18
0
ファイル: base.py プロジェクト: quanlzheng/tensorpack
    def __new__(mcls, name, bases, namespace, **kwargs):

        def hot_patch(required, existing):
            if required not in namespace and existing in namespace:
                namespace[required] = namespace[existing]

        hot_patch('__iter__', 'get_data')
        hot_patch('__len__', 'size')

        return ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
コード例 #19
0
ファイル: codec.py プロジェクト: tstanisl/romanov
 def __new__(mcs, name, bases, namespace):
     cls = ABCMeta.__new__(mcs, name, bases, namespace)
     # dereference to avoid infinite recursion if decorated smt2_encode
     # is called via cls.smt2_encode
     to_wrap = cls.smt2_encode
     @wraps(to_wrap)
     def __wrapper(encodable, encoder):
         "Decorated smt2_encode"
         return encoder.cached_encode(encodable, to_wrap)
     cls.smt2_encode = __wrapper
     return cls
コード例 #20
0
ファイル: subclass.py プロジェクト: CodeMan99/travesty
 def __new__(cls, name, supers, kwargs):
     t = ABCMeta.__new__(cls, name, supers, {})
     # Force __subclass__ to be a classmethod
     # if not isinstance(t.__subclass__, classmethod):
     #     t.__subclass__ = classmethod(_im_func(t.__subclass__))
     if '__subclass__' in kwargs:
         sc = kwargs['__subclass__']
         if not isinstance(sc, classmethod):
             kwargs['__subclass__'] = classmethod(sc)
     t.__subclass__(**kwargs)
     return t
コード例 #21
0
  def __new__(cls, name, bases, attr):
    """ Ensure that subclasses do not carry over previous checks.

    If you import multiple modules in which MonitorDispatcher is subclassed,
    all checks are saved in the global MonitorDispatcher class.
    """
    subclass = ABCMeta.__new__(cls, name, bases, attr)

    subclass.checks = [
      check for check in subclass.checks if check in attr.values()
    ]

    return subclass
コード例 #22
0
ファイル: actions.py プロジェクト: clhunsen/benchbuild
    def __new__(metacls, name, bases, namespace, **kwds):
        result = ABCMeta.__new__(metacls, name, bases, dict(namespace))

        NAME = result.NAME
        DESCRIPTION = result.DESCRIPTION
        if NAME and DESCRIPTION:
            result.__call__ = log_before_after(NAME, DESCRIPTION)(
                    to_step_result(result.__call__)
                )
        else:
            result.__call__ = to_step_result(result.__call__)

        return result
コード例 #23
0
ファイル: namedtuple_with_abc.py プロジェクト: 117111302/poky
 def __new__(mcls, name, bases, namespace):
     fields = namespace.get('_fields')
     for base in bases:
         if fields is not None:
             break
         fields = getattr(base, '_fields', None)
     if not isinstance(fields, abstractproperty):
         basetuple = _namedtuple(name, fields)
         bases = (basetuple,) + bases
         namespace.pop('_fields', None)
         namespace.setdefault('__doc__', basetuple.__doc__)
         namespace.setdefault('__slots__', ())
     return ABCMeta.__new__(mcls, name, bases, namespace)
コード例 #24
0
ファイル: NodeMetaClasses.py プロジェクト: kayhayen/Nuitka
    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)
コード例 #25
0
ファイル: operator.py プロジェクト: LarsWestergren/odl
 def __call__(cls, *args, **kwargs):
     """Create a new class ``cls`` from given arguments."""
     obj = ABCMeta.__call__(cls, *args, **kwargs)
     if not hasattr(obj, 'domain'):
         raise NotImplementedError('`Operator` instances must have a '
                                   '`Operator.domain` attribute.')
     if not hasattr(obj, 'range'):
         raise NotImplementedError('`Operator` instances must have a '
                                   '`Operator.range` attribute.')
     if not hasattr(obj, '_call') and not hasattr(obj, '_apply'):
         raise NotImplementedError('`Operator` instances must either '
                                   'have `_call` or `_apply` as '
                                   'attribute.')
     return obj
コード例 #26
0
ファイル: NodeMetaClasses.py プロジェクト: kayhayen/Nuitka
    def __new__(cls, name, bases, dictionary):  # pylint: disable=I0021,arguments-differ
        _checkBases(name, bases)

        if "__slots__" not in dictionary:
            dictionary["__slots__"] = ()

        if "named_child" in dictionary:
            dictionary["__slots__"] += (intern("subnode_" + dictionary["named_child"]),)

        # Not a method:
        if "checker" in dictionary:
            dictionary["checker"] = staticmethod(dictionary["checker"])

        # false alarm, pylint: disable=I0021,too-many-function-args
        return ABCMeta.__new__(cls, name, bases, dictionary)
コード例 #27
0
ファイル: core.py プロジェクト: jooon/pyschema
    def __new__(metacls, name, bases, dct):
        schema_attrs = metacls._get_schema_attributes(
            name=name,
            bases=bases,
            dct=dct
        )
        dct.update(schema_attrs)
        cls = ABCMeta.__new__(metacls, name, bases, dct)

        # allow self-references etc.
        for field_name, field in cls._fields.iteritems():
            field.set_parent(cls)

        if metacls.auto_register:
            auto_store.add_record(cls, _bump_stack_level=True)
        return cls
コード例 #28
0
ファイル: parser_common.py プロジェクト: tsnoam/Flexget
class ParsedMovie(ABCMeta(str('ParsedMovieABCMeta'), (ParsedVideo,), {})):
    @property
    def parsed_name(self):
        return self.title

    @property
    def type(self):
        return 'movie'

    @property
    def title(self):
        raise NotImplementedError

    @property
    def is_movie(self):
        return True
コード例 #29
0
ファイル: NodeMetaClasses.py プロジェクト: swissvoc/Nuitka
    def __new__(cls, name, bases, dictionary):  # pylint: disable=I0021,arguments-differ
        _checkBases(name, bases)

        if "__slots__" not in dictionary:
            dictionary["__slots__"] = ()

        if "named_child" in dictionary:
            dictionary["__slots__"] += (intern("subnode_" +
                                               dictionary["named_child"]), )

        # Not a method:
        if "checker" in dictionary:
            dictionary["checker"] = staticmethod(dictionary["checker"])

        # false alarm, pylint: disable=I0021,too-many-function-args
        return ABCMeta.__new__(cls, name, bases, dictionary)
コード例 #30
0
def test_cachedmethod_maintains_func_abstraction():
    ABC = ABCMeta('ABC', (object,), {})

    class Car(ABC):

        def __init__(self, cache=None):
            self.h_cache = LRI() if cache is None else cache
            self.hand_count = 0

        @cachedmethod('h_cache')
        @abstractmethod
        def hand(self, *a, **kw):
            self.hand_count += 1

    with pytest.raises(TypeError):
        Car()
コード例 #31
0
ファイル: core.py プロジェクト: nkabir/pyschema
    def __new__(metacls, name, bases, dct):
        schema_attrs = metacls._get_schema_attributes(
            name=name,
            bases=bases,
            dct=dct
        )
        dct.update(schema_attrs)
        cls = ABCMeta.__new__(metacls, name, bases, dct)

        # allow self-references etc.
        for field_name, field in cls._fields.iteritems():
            field.set_parent(cls)

        if metacls.auto_register:
            auto_store.add_record(cls, _bump_stack_level=True)
        return cls
コード例 #32
0
ファイル: common.py プロジェクト: pombredanne/python-anyvcs
 def __new__(meta, name, bases, clsdict):
   if not('__doc__' in clsdict and clsdict['__doc__']):
     for mro_cls in (mro_cls for base in bases for mro_cls in base.mro()):
       doc = mro_cls.__doc__
       if doc:
         clsdict['__doc__'] = doc
         break
   for attr, attribute in clsdict.items():
     if not attribute.__doc__:
       for mro_cls in (mro_cls for base in bases for mro_cls in base.mro()
                       if hasattr(mro_cls, attr)):
         doc=getattr(getattr(mro_cls, attr), '__doc__')
         if doc:
           attribute.__doc__ = doc
           break
   return ABCMeta.__new__(meta, name, bases, clsdict)
コード例 #33
0
	def __new__(mcs, name, bases, attrs, **kwargs):
		# Prepare __slots__
		attrs["__slots__"]=[]

		# If some parameters are defined
		if "__ATTRIBUTES__" in attrs.keys():
			for parameter in attrs["__ATTRIBUTES__"]:

				# Create a slot for each
				attrs["__slots__"].append("_"+parameter.id)

				# And create a descriptor class to handle their
				# get/set/default/doc based on parameter description
				class Descriptor(object):
					__doc__ ="""%s

					Default: %s

					"""%(parameter.description,\
					    str(parameter.default) if parameter.default != "" else "\"\"")

					__slots__ = ["_parameter"]

					def __init__(self, parameter):
						self._parameter = parameter

					def __get__(self, instance, owner):
						if instance is not None:
							try:
								return getattr(instance, "_"+self._parameter.id)
							except AttributeError:
								setattr(instance, "_"+self._parameter.id, self._parameter.normalizer(self._parameter.default))
								return getattr(instance, "_"+self._parameter.id)
						else:
							return self._parameter

					def __set__(self, instance, value):
						new_value = value if value is not None and value != "" else self._parameter.default
						new_value = self._parameter.normalizer(new_value)
						return setattr(instance, "_"+self._parameter.id, new_value)

					def __delete__(self, instance):
						return setattr(instance, "_"+self._parameter.id, self._parameter.normalizer(self._parameter.default))

				attrs[parameter.id] = Descriptor(parameter)

		return ABCMeta.__new__(mcs, name, bases, attrs)
コード例 #34
0
    def schema_constructor(self, atomic_type, bp=90):
        """Registers a token class for a schema atomic type constructor function."""
        if atomic_type in {XSD_ANY_ATOMIC_TYPE, XSD_NOTATION}:
            raise xpath_error('XPST0080')

        def nud_(self_):
            self_.parser.advance('(')
            self_[0:] = self_.parser.expression(5),
            self_.parser.advance(')')

            try:
                self_.value = self_.evaluate()  # Static context evaluation
            except MissingContextError:
                self_.value = None
            return self_

        def evaluate_(self_, context=None):
            arg = self_.get_argument(context)
            if arg is None:
                return []

            value = self_.string_value(arg)
            try:
                return self_.parser.schema.cast_as(value, atomic_type)
            except (TypeError, ValueError) as err:
                raise self_.error('FORG0001', err)

        symbol = get_prefixed_name(atomic_type, self.namespaces)
        token_class_name = str("_%s_constructor_token" %
                               symbol.replace(':', '_'))
        kwargs = {
            'symbol': symbol,
            'label': 'constructor function',
            'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol,
            'lbp': bp,
            'rbp': bp,
            'nud': nud_,
            'evaluate': evaluate_,
            '__module__': self.__module__,
            '__qualname__': token_class_name,
            '__return__': None
        }
        token_class = ABCMeta(token_class_name, (self.token_base_class, ),
                              kwargs)
        MutableSequence.register(token_class)
        self.symbol_table[symbol] = token_class
        return token_class
コード例 #35
0
class six(object):
    """
    A light-weight version of six (which works on IronPython)
    """
    PY3 = sys.version_info[0] >= 3
    ABC = ABCMeta('ABC', (object,), {'__module__':__name__, '__slots__':()})

    # Be sure to use named-tuple access, so that usage is not affected
    try:
        getfullargspec = staticmethod(inspect.getfullargspec)
    except AttributeError:
        getfullargspec = staticmethod(inspect.getargspec) # extra fields will not be available

    if PY3:
        integer_types = (int,)
        string_types = (str,)
        MAXSIZE = sys.maxsize
        ascii = ascii  # @UndefinedVariable
        bytes = bytes  # @ReservedAssignment
        unicode_type = str

        @staticmethod
        def b(s):
            return s.encode("latin-1", "replace")
        @staticmethod
        def u(s):
            return s
        @staticmethod
        def get_method_function(m):
            return m.__func__
    else:
        integer_types = (int, long)
        string_types = (str, unicode)
        MAXSIZE = getattr(sys, "maxsize", sys.maxint)
        ascii = repr  # @ReservedAssignment
        bytes = str   # @ReservedAssignment
        unicode_type = unicode

        @staticmethod
        def b(st):
            return st
        @staticmethod
        def u(s):
            return s.decode("unicode-escape")
        @staticmethod
        def get_method_function(m):
            return m.im_func
コード例 #36
0
ファイル: fields.py プロジェクト: ericb/ciri
    def __new__(cls, name, bases, attrs):
        klass = ABCMeta.__new__(cls, name, bases, dict(attrs))
        if isinstance(attrs.get('messages'), FieldErrorMessages):
            klass.messages = attrs.get('messages')
        else:
            klass.messages = FieldErrorMessages(**attrs.get('messages', {}))
        if getattr(klass, 'new', None):
            constructor = klass.__init__
            new_constructor = klass.new

            def field_init(self, *args, **kwargs):
                constructor(self, *args, **kwargs)
                new_constructor(self, *args, **kwargs)

            klass.__init__ = field_init
            delattr(klass, 'new')
        return klass
コード例 #37
0
    def __new__(mcs, *args, **kwargs):
        result = ABCMeta.__new__(mcs, *args, **kwargs)
        if result.required_extras is not None:
            result.__init__ = requires(result.required_extras)(result.__init__)

            patterns = ["load_from_checkpoint",
                        "available_*"]  # must match classmethods only
            regex = "(" + ")|(".join(patterns) + ")"
            for attribute_name, attribute_value in filter(
                    lambda x: re.match(regex, x[0]),
                    inspect.getmembers(result)):
                setattr(
                    result, attribute_name,
                    classmethod(
                        requires(result.required_extras)(
                            attribute_value.__func__)))
        return result
コード例 #38
0
ファイル: fields.py プロジェクト: ericb/ciri
    def __new__(cls, name, bases, attrs):
        klass = ABCMeta.__new__(cls, name, bases, dict(attrs))
        if isinstance(attrs.get('messages'), FieldErrorMessages):
            klass.messages = attrs.get('messages')
        else:
            klass.messages = FieldErrorMessages(**attrs.get('messages', {}))
        if getattr(klass, 'new', None):
            constructor = klass.__init__
            new_constructor = klass.new

            def field_init(self, *args, **kwargs):
                constructor(self, *args, **kwargs)
                new_constructor(self, *args, **kwargs)

            klass.__init__ = field_init
            delattr(klass, 'new')
        return klass
コード例 #39
0
    def __new__(mcs, name, bases, namespace, **kwargs):
        from aiida.plugins.entry_point import get_entry_point_from_class

        newcls = ABCMeta.__new__(mcs, name, bases, namespace, **kwargs)  # pylint: disable=too-many-function-args

        entry_point_group, entry_point = get_entry_point_from_class(
            namespace['__module__'], name)

        if entry_point_group is None or entry_point_group != 'aiida.groups':
            newcls._type_string = None
            message = 'no registered entry point for `{}` so its instances will not be storable.'.format(
                name)
            warnings.warn(message)  # pylint: disable=no-member
        else:
            newcls._type_string = entry_point.name  # pylint: disable=protected-access

        return newcls
コード例 #40
0
    def __new__(
            mcls, name, bases,
            namespace):  # When a new class is created, that has this metaclass
        missingMethods = []  # Hold all methods missing
        wrongSignature = []  # Hold all methods having wrong signature

        if not name in ['MaskingObject', 'MultiMask'
                        ]:  # If MaskingObject, then just continue

            if not '__call__' in namespace:  # Check if __call__ exists
                missingMethods.append('__call__')

            if namespace['dimensionality'] == '2D' or namespace[
                    'dimensionality'] == '3D':
                if 'plot' in namespace:  # Check if plot has the right signature

                    callFunction = namespace['plot']
                    requiredNames = ['ax', 'transformation']
                    notInSignature = requiredArguments(callFunction,
                                                       requiredNames)
                    if len(notInSignature) > 0:
                        wrongSignature.append(
                            ['plot', requiredNames, notInSignature])
                else:
                    missingMethods.append('plot')

            # Write error report
            ErrorMessage = []
            if len(missingMethods) > 0:
                ErrorMessage.append(
                    "Can't instantiate abstract class {} with abstract methods\n"
                    .format(name) + ', '.join(missingMethods))

            for entry in wrongSignature:
                methodName = entry[0]
                requiredNames = entry[1]
                notInSignature = entry[2]
                ErrorMessage.append(
                    'The "{}" method on "{}" must have all of the following arguments in call signature [{}]. Following are missing: [{}]'
                    .format(methodName, name, ', '.join(requiredNames),
                            ', '.join(notInSignature)))
            if len(ErrorMessage) > 0:
                raise TypeError('\n'.join(ErrorMessage))

        return ABCMeta.__new__(mcls, name, bases, namespace)
コード例 #41
0
ファイル: lib.py プロジェクト: tigrawap/plumbum
class six(object):
    """
    A light-weight version of six (which works on IronPython)
    """
    PY3 = sys.version_info[0] >= 3
    ABC = ABCMeta('ABC', (object, ), {'__module__': __name__})

    if PY3:
        integer_types = (int, )
        string_types = (str, )
        MAXSIZE = sys.maxsize
        ascii = ascii  # @UndefinedVariable
        bytes = bytes  # @ReservedAssignment
        unicode_type = str

        @staticmethod
        def b(s):
            return s.encode("latin-1", "replace")

        @staticmethod
        def u(s):
            return s

        @staticmethod
        def get_method_function(m):
            return m.__func__
    else:
        integer_types = (int, long)
        string_types = (str, unicode)
        MAXSIZE = getattr(sys, "maxsize", sys.maxint)
        ascii = repr  # @ReservedAssignment
        bytes = str  # @ReservedAssignment
        unicode_type = unicode

        @staticmethod
        def b(st):
            return st

        @staticmethod
        def u(s):
            return s.decode("unicode-escape")

        @staticmethod
        def get_method_function(m):
            return m.im_func
コード例 #42
0
ファイル: NodeBases.py プロジェクト: vt100/Nuitka
    def __new__(cls, name, bases, dictionary):
        # This is in conflict with either PyDev or Pylint, pylint: disable=C0204
        assert len(bases) == len(set(bases)), bases

        last_mixin = None
        for base in bases:
            base_name = base.__name__
            is_mixin = base_name.endswith("Mixin")

            if is_mixin and last_mixin is False:
                assert False, (name, bases)

            last_mixin = is_mixin

        if "__slots__" not in dictionary:
            dictionary["__slots__"] = ()

        return ABCMeta.__new__(cls, name, bases, dictionary)
コード例 #43
0
 def __new__(meta, name, bases, clsdict):
     if not ('__doc__' in clsdict and clsdict['__doc__']):
         for mro_cls in (mro_cls for base in bases
                         for mro_cls in base.mro()):
             doc = mro_cls.__doc__
             if doc:
                 clsdict['__doc__'] = doc
                 break
     for attr, attribute in clsdict.items():
         if not attribute.__doc__:
             for mro_cls in (mro_cls for base in bases
                             for mro_cls in base.mro()
                             if hasattr(mro_cls, attr)):
                 doc = getattr(getattr(mro_cls, attr), '__doc__')
                 if doc:
                     attribute.__doc__ = doc
                     break
     return ABCMeta.__new__(meta, name, bases, clsdict)
コード例 #44
0
ファイル: game_object_class.py プロジェクト: Sponja-/RimWorld
    def __new__(
        cls: Type["GameObject"],
        clsname: str,
        bases: Tuple[Type["GameObject"], ...],
        namespace: Dict[str, Any],
    ) -> "GameObjectMeta":

        # Events and handlers

        event_handlers: Dict[str, OrderedSet] = defaultdict(OrderedSet)
        if clsname != "GameObject":
            for base in bases:
                for eventName, handlers in base.__handlers__.items():
                    event_handlers[eventName] |= handlers

        for name, value in namespace.items():
            if isinstance(value, Event):
                if value.name is None:
                    value.name = name
                event_handlers[name] = OrderedSet([])

        to_delete: List[Callable] = []
        for name, value in namespace.items():
            if hasattr(value, "__target__"):
                if value.__target__ in event_handlers:
                    event_handlers[value.__target__].add(value)
                else:
                    raise NameError(f"Unknown event: {value.__target__}")

        for name in to_delete:
            del namespace[name]

        # Attributes

        for name, value in namespace.items():
            if isinstance(value, Attribute):
                if value.name is None:
                    value.name = name

        new_cls = ABCMeta.__new__(cls, clsname, bases, namespace)

        new_cls.__handlers__ = dict(event_handlers)

        return new_cls
コード例 #45
0
 def __new__(mcs: Type[TT], *args: Any, **kwargs: Any) -> TT:
     try:
         class_annotations = args[2]["__annotations__"]
     except KeyError:
         class_annotations = None
         annotations_mention_id = False
     else:
         try:
             class_annotations.pop("id")
         except KeyError:
             annotations_mention_id = False
         else:
             annotations_mention_id = True
     cls = ABCMeta.__new__(mcs, *args)
     if class_annotations:
         cls = dataclass(eq=False, repr=False)(cls)
     if annotations_mention_id:
         _annotations_mention_id.add(cls)
     return cls
コード例 #46
0
ファイル: operator.py プロジェクト: burgerdev/lazyflow
 def __call__(cls, *args, **kwargs):
     # type.__call__ calls instance.__init__ internally
     try:
         instance = ABCMeta.__call__(cls, *args, **kwargs)
     except Exception as e:
         err = "Could not create instance of '{}'\n".format(cls)
         err += "args   = {}\n".format(args)
         err += "kwargs = {}\n".format(kwargs)
         err += "The exception was:\n"
         err += str(e)
         err += "\nTraceback:\n"
         import traceback
         import StringIO
         s = StringIO.StringIO()
         traceback.print_exc(file=s)
         err += s.getvalue()
         raise RuntimeError(err)
     instance._after_init()
     return instance
コード例 #47
0
ファイル: parser_common.py プロジェクト: edetaillac/Flexget
class ParsedVideoQuality(
        ABCMeta(native_str('ParsedVideoQualityABCMeta'), (object, ), {})):
    @abstractproperty
    def screen_size(self):
        raise NotImplementedError

    @abstractproperty
    def source(self):
        raise NotImplementedError

    @abstractproperty
    def format(self):
        raise NotImplementedError

    @abstractproperty
    def video_codec(self):
        raise NotImplementedError

    @abstractproperty
    def video_profile(self):
        raise NotImplementedError

    @abstractproperty
    def audio_codec(self):
        raise NotImplementedError

    @abstractproperty
    def audio_profile(self):
        raise NotImplementedError

    @abstractproperty
    def audio_channels(self):
        raise NotImplementedError

    @abstractmethod
    def to_old_quality(self, assumed_quality=None):
        raise NotImplementedError

    def __str__(self):
        return "<%s(screen_size=%s,source=%s,video_codec=%s,audio_channels=%s)>" % (
            self.__class__.__name__, self.screen_size, self.source,
            self.video_codec, self.audio_channels)
コード例 #48
0
ファイル: core.py プロジェクト: patrick-ryan/ciri
 def __new__(cls, name, bases, attrs):
     cls, name, bases, attrs = cls.prepare_class(cls, name, bases, attrs)
     klass = ABCMeta.__new__(cls, name, bases, dict(attrs))
     klass._fields = {}
     klass._tags = {}
     klass._subschemas = {}
     klass._pending_schemas = {}
     klass._load_keys = {}
     klass._schema_callables = SchemaCallableObject()
     klass._field_callables = FieldCallableObject()
     klass._config = DEFAULT_SCHEMA_OPTIONS
     klass.handle_bases(bases)
     klass.handle_poly(cls, name, bases, attrs)
     klass.handle_config()
     klass.handle_tags()
     klass.find_fields()
     klass.process_fields()
     klass._schema_callables.find(klass)
     klass._field_callables.find(klass)
     return klass
コード例 #49
0
class MessageSink(ABCMeta('ABCMeta', (object, ), {})):
    """A base class for all message sinks.

  MessageSinks form a cooperative linked list, which each sink calling the
  next sink in the chain once it's processing is complete.
  """
    __slots__ = '_next',

    def __init__(self):
        super(MessageSink, self).__init__()
        self._next = None

    @property
    def next_sink(self):
        """The next sink in the chain."""
        return self._next

    @next_sink.setter
    def next_sink(self, value):
        self._next = value
コード例 #50
0
class Item(ABCMeta('ABC', (object, ), {'__slots__': ()})):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.active = True
        self.id = id(self)
        self.name = self.__class__.__name__
        self.logic_attribute_name_list = [
            'logic_attribute_name_list', 'name', 'id', 'x', 'y', 'alive'
        ]

    def __getstate__(self):
        state = self.__dict__.copy()
        newstate = {k: state[k] for k in self.logic_attribute_name_list}
        return newstate

    def __setstate__(self, state):
        self.__dict__.update(state)

    @abstractmethod
    def use(self, benefitor):
        pass
コード例 #51
0
ファイル: NodeMetaClasses.py プロジェクト: xlizzard/Nuitka
    def __new__(cls, name, bases, dictionary):  # pylint: disable=I0021,arguments-differ
        _checkBases(name, bases)

        if "__slots__" not in dictionary:
            dictionary["__slots__"] = ()

        if "named_child" in dictionary:
            dictionary["__slots__"] += (intern("subnode_" +
                                               dictionary["named_child"]), )

        if "named_children" in dictionary and not name.endswith("Base"):
            if len(dictionary["named_children"]) <= 1:
                raise NuitkaNodeDesignError(
                    name,
                    "Use ExpressionChildHaving for one child node classes")

        # Not a method:
        if "checker" in dictionary:
            dictionary["checker"] = staticmethod(dictionary["checker"])

        # false alarm, pylint: disable=I0021,too-many-function-args
        return ABCMeta.__new__(cls, name, bases, dictionary)
コード例 #52
0
    def __new__(mcls, name, bases, dct):
        base_types = [b for b in bases if isinstance(b, Context)]
        if len(base_types) > 1:
            raise TypeError(
                "Cannot resolve inheritance of multiple context types")
        elif len(base_types) == 1:
            parent = base_types[0]
            base_type = parent.base_type
            base_context = parent._context
            instances = parent._instances
        else:
            # This is for a base context type.
            base_type = None
            base_context = None
            instances = []

        dct = mcls.__new_init(dct)
        cls = ABCMeta.__new__(mcls, name, bases, dct)
        cls._instances = instances
        cls.base_type = base_type
        cls._context = base_context
        return cls
コード例 #53
0
ファイル: base.py プロジェクト: riga/law
    def __new__(metacls, classname, bases, classdict):
        # default attributes, irrespective of inheritance
        classdict.setdefault("exclude_index", False)

        # unite "exclude_params_*" sets with those of all base classes
        for base in bases:
            for attr, base_params in vars(base).items():
                if attr.startswith("exclude_params_") and isinstance(
                        base_params, set):
                    params = classdict.setdefault(attr, set())
                    if isinstance(params, set):
                        params.update(base_params)

        # remove those parameter names from "exclude_params_*" sets which are explicitly
        # listed in corresponding "include_params_*" sets defined on the class itself
        for attr, include_params in classdict.items():
            if attr.startswith("include_params_") and isinstance(
                    include_params, set):
                exclude_attr = "exclude" + attr[len("include"):]
                if exclude_attr in classdict and isinstance(
                        classdict[exclude_attr], set):
                    classdict[exclude_attr] -= include_params

        # create the class
        cls = ABCMeta.__new__(metacls, classname, bases, classdict)

        # default attributes, apart from inheritance
        if getattr(cls, "update_register", None) is None:
            cls.update_register = False

        # deregister when requested
        if cls.update_register:
            cls.deregister()

        # add to register (mimic luigi.task_register.Register.__new__)
        cls._namespace_at_class_time = metacls._get_namespace(cls.__module__)
        metacls._reg.append(cls)

        return cls
コード例 #54
0
ファイル: element.py プロジェクト: goblin-ogm/goblin
 def __new__(cls, name, bases, namespace, **kwds):
     props = {}
     if name == 'VertexProperty':
         element_type = name.lower()
     elif bases:
         element_type = bases[0].__type__
         if element_type not in ['vertex', 'edge']:
             element_type = bases[0].__name__.lower()
         for base in bases:
             base_props = getattr(base, '__properties__', {})
             props.update(base_props)
     else:
         element_type = name.lower()
     namespace['__type__'] = element_type
     if not namespace.get('__label__', None):
         namespace['__label__'] = inflection.underscore(name)
     new_namespace = {}
     props.pop('id', None)
     for k, v in namespace.items():
         if isinstance(v, abc.BaseProperty):
             if element_type == 'edge' and hasattr(v, 'cardinality'):
                 raise exception.MappingError(
                     'Edge property cannot have set/list cardinality')
             props[k] = v
             if k != 'id':
                 if not v.db_name:
                     v.db_name = v.db_name_factory(k,
                                                   namespace['__label__'])
             v = v.__descriptor__(k, v)
         new_namespace[k] = v
     new_namespace['__mapping__'] = mapper.create_mapping(namespace, props)
     new_namespace['__properties__'] = props
     new_namespace['__immutable__'] = namespace.get('__immutable__',
                                                    ImmutableMode.OFF)
     new_namespace['__locking__'] = namespace.get('__locking__',
                                                  LockingMode.OFF)
     result = ABCMeta.__new__(cls, name, bases, new_namespace)
     return result
コード例 #55
0
ファイル: operator.py プロジェクト: thatcher/lazyflow
 def __call__(cls, *args, **kwargs):
     # type.__call__ calls instance.__init__ internally
     try:
         instance = ABCMeta.__call__(cls, *args, **kwargs)
     except Exception as e:
         # FIXME: What is the point of this long exception message?
         # Why can't we just let the exception propagate up the stack?
         # Is it because of some weird interaction between this metaclass and the Qt event loop?
         # ....probably
         err = "Could not create instance of '{}'\n".format(cls)
         err += "args   = {}\n".format(args)
         err += "kwargs = {}\n".format(kwargs)
         err += "The exception was:\n"
         err += str(e)
         err += "\nTraceback:\n"
         import traceback
         import StringIO
         s = StringIO.StringIO()
         traceback.print_exc(file=s)
         err += s.getvalue()
         raise RuntimeError(err)
     instance._after_init()
     return instance
コード例 #56
0
ファイル: descriptor.py プロジェクト: cristidomsa/Ally-Py
def processAsService(clazz, service):
    '''
    Processes the provided class as a service.
    
    @param clazz: class
        The class to be processed.
    @param service: TypeService
        The service to process with.
    @return: class
        The processed class.
    '''
    assert isclass(clazz), 'Invalid class %s' % clazz
    assert isinstance(service, TypeService), 'Invalid service %s' % service

    if type(clazz) != ABCMeta:
        attributes = dict(clazz.__dict__)
        attributes.pop(
            '__dict__', None
        )  # Removing __dict__ since is a reference to the old class dictionary.
        attributes.pop('__weakref__', None)
        clazz = service.clazz = ABCMeta(clazz.__name__, clazz.__bases__,
                                        attributes)

    abstract = set(clazz.__abstractmethods__)
    abstract.update(service.calls)

    clazz.__abstractmethods__ = frozenset(abstract)
    for name, callType in service.calls.items():
        callAPI = CallAPI(callType)
        callAPI.__isabstractmethod__ = True  # Flag that notifies the ABCMeta that is is an actual abstract method.
        # We provide the original function code and name.
        callAPI.__code__ = getattr(clazz, name).__code__
        callAPI.__name__ = getattr(clazz, name).__name__
        updateWrapper(callAPI, getattr(clazz, name))
        setattr(clazz, name, callAPI)

    return clazz
コード例 #57
0
# For the licensing terms see $ROOTSYS/LICENSE.                                #
# For the list of contributors see $ROOTSYS/README/CREDITS.                    #
################################################################################

import functools
from abc import ABCMeta
from abc import abstractmethod

import ROOT
from DistRDF.Backends import Utils
from DistRDF.HeadNode import TreeHeadNode

# Abstract class declaration
# This ensures compatibility between Python 2 and 3 versions, since in
# Python 2 there is no ABC class
ABC = ABCMeta("ABC", (object, ), {})


class BaseBackend(ABC):
    """
    Base class for RDataFrame distributed backends.

    Attributes:
        supported_operations (list): List of operations supported by the
            backend.
        initialization (function): Store user's initialization method, if
            defined.
        headers (list): List of headers that need to be declared for the
            analysis.
        shared_libraries (list): List of shared libraries needed for the
            analysis.
コード例 #58
0
ファイル: widgets.py プロジェクト: yyg192/adv-dnn-ens-malware
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""Default ProgressBar widgets."""

from __future__ import division

import datetime
import math

try:
    from abc import ABCMeta, abstractmethod
except ImportError:
    AbstractWidget = object
    abstractmethod = lambda fn: fn
else:
    AbstractWidget = ABCMeta('AbstractWidget', (object, ), {})


def format_updatable(updatable, pbar):
    if hasattr(updatable, 'update'): return updatable.update(pbar)
    else: return updatable


class Widget(AbstractWidget):
    """The base class for all widgets.

    The ProgressBar will call the widget's update value when the widget should
    be updated. The widget's size may change between calls, but the widget may
    display incorrectly if the size changes drastically and repeatedly.

    The boolean TIME_SENSITIVE informs the ProgressBar that it should be
コード例 #59
0
PY2 = sys.version_info[0] == 2

if not PY2:  # pragma: no cover
    from abc import ABC

    text_type = str
    string_types = (str, )
    integer_types = (int, )
    intern_method = sys.intern
    range_method = range
    iterkeys = lambda d: iter(d.keys())
    itervalues = lambda d: iter(d.values())
    iteritems = lambda d: iter(d.items())
else:  # pragma: no cover
    from abc import ABCMeta
    ABC = ABCMeta('ABC', (object, ), {})
    text_type = unicode
    string_types = (str, unicode)
    integer_types = (int, long)
    intern_method = intern
    range_method = xrange
    iterkeys = lambda d: d.iterkeys()
    itervalues = lambda d: d.itervalues()
    iteritems = lambda d: d.iteritems()


def to_bytes(text, encoding='utf-8'):
    """Transform string to bytes."""
    if isinstance(text, text_type):
        text = text.encode(encoding)
    return text
コード例 #60
0
 def __subclasscheck__(cls, subclass):
     try:
         return ABCMeta.__subclasscheck__(cls, subclass)
     except TypeError:
         return False