def _add_pixel_comparison_operator_methods(pixel_comparison_op_cls): pixel_comparison_op_cls.input_image_to_repr = abstractmethod( _comparison_input_image_to_repr) pixel_comparison_op_cls.input_enc_to_repr = _comparison_input_enc_to_repr pixel_comparison_op_cls.target_image_to_repr = abstractmethod( _target_image_to_repr) pixel_comparison_op_cls.target_enc_to_repr = _target_enc_to_repr return pixel_comparison_op_cls
class User(ControllerBase): def list(self, project_id=None): return self._list(project_id) _list = abc.abstractmethod(lambda x: None) def get(self, name, project_id=None): return self._get(name, project_id) _get = abc.abstractmethod(lambda x: None)
class ValidatorInterface(object): __metaclass__ = abc.ABCMeta exception = abc.abstractproperty(lambda *args, **kwargs: NotImplemented) message = abc.abstractmethod(lambda *args, **kwargs: NotImplemented) __instancecheck__ = abc.abstractmethod( lambda *args, **kwargs: NotImplemented) def validate(self, obj, name="object"): """Mixin - non-abstract method.""" if self.__instancecheck__(self, obj): raise self.exception(self.message(obj, name=name)) return obj
def abstractproperty(f): if version_info >= (3, 3): from abc import abstractmethod return property(abstractmethod(f)) else: from abc import abstractproperty return abstractproperty(f)
def abstractstyle(callable_object: _AnyCallable) -> _AnyCallable: """A decorator indicating abstract style methods. An AbstractStyle class cannot be instantiated unless all of its abstract methods are overridden. Args: callable_object (Callable[[Any, ...], Any]): Returns: a callable object Example: >>> class Base(AbstractStyle): ... @abstractstyle ... def name(self) -> None: ... pass ... ... ... class Child(Base): ... pass ... ... >>> Child() ... TypeError: Can't instantiate abstract class Base with abstract methods name """ return abc.abstractmethod(callable_object)
def abstractproperty(func): """ Define abstract properties for both python 2 and 3. """ if sys.version_info > (3, 3): return property(abc.abstractmethod(func)) return abc.abstractproperty(func)
def create( cls, listening_events: List[Type[BaseEvent]], using_dispatchers: List[T_Dispatcher] = None, using_decorators: List[Decorater] = None, priority: int = 15, # 默认情况下都是需要高于默认 16 的监听吧... enable_internal_access: bool = False, block_propagation: bool = False, ) -> Type["Waiter"]: async def detected_event(self) -> Any: pass return type( "AbstractWaiter", (cls, ), { "listening_events": listening_events, "using_dispatchers": using_dispatchers, "using_decorators": using_decorators, "priority": priority, "enable_internal_access": enable_internal_access, "block_propagation": block_propagation, "detected_event": abstractmethod(detected_event), }, )
def __init__(self, default_callable, is_abstractmethod=False): self._obj = None if is_abstractmethod: self._default_callable = abstractmethod(default_callable) else: self._default_callable = default_callable self.registered = dict()
def generate_abstract_container(class_naming: NamedProperty, item_naming: Naming): template = InterfaceGenerator.get_class_template(class_naming.naming) items_name = str(item_naming.plural_value_name) def getter(self): raise NotImplementedError( "Getter for property {} is not impplemented".format( items_name)) getter.__name__ = items_name getter = abstractmethod(getter) doc_str = "Returns all contained {} of the {} instance.".format( item_naming.docstring_name, class_naming.naming.docstring_name) setattr(template, items_name, getter) p = property(fget=getter, doc=doc_str) setattr(template, items_name, p) template.__abstractmethods__ = frozenset([items_name]) #print(template.knives) return template
def abstract(obj): """Decorator""" if inspect.isfunction(obj): return abc.abstractmethod(obj); elif isinstance(obj, type(OOPMeta)): return abstractclass(obj); return obj;
def classmethod(func): """Wrap a function as a classmethod. This applies the classmethod decorator. """ attr = abc.abstractmethod(func) attr.__iclassmethod__ = True attr = _classmethod(attr) return attr
def api_required(func): """A decorator to mark a function as abstract and requiring a backend implementation.""" func.__doc__ = _append_to_docstring(func.__doc__, textwrap.dedent(""" *This is an abstract method. Backends must implement this method* """)) return abc.abstractmethod(func)
def abstract_property(func): """ Abstract property decorator. :param func: method to decorate :type func: callable :returns: decorated function :rtype: callable """ return property(abstractmethod(func))
def classattribute(func): """Wrap a function as a class attribute. This differs from attribute by identifying attributes explicitly listed in a class definition rather than those only defined on instances of a class. """ attr = abc.abstractmethod(func) attr.__iclassattribute__ = True attr = _property(attr) return attr
def property(func): """Wrap a function as a property. This differs from attribute by identifying properties explicitly listed in the class definition rather than named attributes defined on instances of a class at init time. """ attr = abc.abstractmethod(func) attr.__iproperty__ = True attr = Property(attr) return attr
def abstractmethod(func): """ A decorator indicating abstract methods. Args: func: The function object to decorate Returns: The decorated function """ return abc.abstractmethod(func)
def abstract_property(func): """ Python2/3 compatible abstract property decorator. :param func: method to decorate :type func: callable :returns: decorated function :rtype: callable """ return (property(abstractmethod(func)) if sys.version_info > (3, 3) else abstractproperty(func))
def __new__(mcls, name, bases, namespace, **kwargs): # noqa: N804 cls = super().__new__(mcls, name, bases, namespace, **kwargs) base_func = cls.__call__ def pre_call(obj, traces): @preprocess def _(traces): return base_func(obj, traces) return _(traces) cls.__call__ = abc.abstractmethod(pre_call) return cls
def api_required(func): """A decorator to mark a function as abstract and requiring a backend implementation.""" func.__doc__ = _append_to_docstring( func.__doc__, textwrap.dedent(""" *This is an abstract method. Backends must implement this method* """)) return abc.abstractmethod(func)
def __new__(mcls, cls_name, bases, namespace): #pylint: disable=C0202 if not '__abstractmethods__' in namespace: raise TypeError("{0} missing required property: __abstractmethods__") # Create function stubs # ... is this unnecessary ??? for name in namespace.get('__abstractmethods__', frozenset([])): namespace[name] = abc.abstractmethod(lambda *a,**kw: NotImplemented) cls = super(DuckMeta, mcls).__new__(mcls, cls_name, bases, namespace) return cls
class Step(abc.ABC): name: property(abc.abstractmethod(lambda _:...)) state: property(abc.abstractmethod(lambda _:...)) method: property(abc.abstractmethod(lambda _:...)) catelog = dict() @staticmethod def order(steps): if isinstance(steps, str): return (yield from Step.order([steps])) for _step in ("pre", "index", "post"): if _step in steps: yield _step def __init__(self, indexer): self.indexer = indexer self.state = self.state(get_src_build(), indexer.build_name, indexer.es_index_name, logfile=indexer.logfile) @classmethod def __init_subclass__(cls): cls.catelog[cls.name] = cls @classmethod def dispatch(cls, name): return cls.catelog[name] @asyncio.coroutine def execute(self, *args, **kwargs): coro = getattr(self.indexer, self.method) coro = coro(*args, **kwargs) return (yield from coro) def __str__(self): return (f"<Step" f" name='{self.name}'" f" indexer={self.indexer}" f">")
def test_abstract_subclasses(self): AbstractSubclass = ABCMeta('AbstractSubclass', (greenlet, ), {'run': abstractmethod(lambda self: None)}) class BadSubclass(AbstractSubclass): pass class GoodSubclass(AbstractSubclass): def run(self): pass GoodSubclass() # should not raise self.assertRaises(TypeError, BadSubclass)
def _ensure_everything_is_abstract(attributes): # all methods and properties are abstract on a pure interface namespace = {} functions = [] interface_method_signatures = {} interface_property_names = set() interface_attribute_names = set() for name, value in six.iteritems(attributes): if _builtin_attrs(name): pass # shortcut elif name == '__annotations__': interface_attribute_names.update(value.keys()) elif value is None: interface_attribute_names.add(name) continue # do not add to class namespace elif getattr(value, '__isabstractmethod__', False): if isinstance(value, (staticmethod, classmethod, types.FunctionType)): if isinstance(value, (staticmethod, classmethod)): func = value.__func__ else: func = value functions.append(func) interface_method_signatures[name] = getargspec(func) elif isinstance(value, property): interface_property_names.add(name) elif isinstance(value, staticmethod): func = value.__func__ functions.append(func) interface_method_signatures[name] = getargspec(func) value = abstractstaticmethod(func) elif isinstance(value, classmethod): func = value.__func__ interface_method_signatures[name] = getargspec(func) functions.append(func) value = abstractclassmethod(func) elif isinstance(value, types.FunctionType): functions.append(value) interface_method_signatures[name] = getargspec(value) value = abstractmethod(value) elif isinstance(value, property): interface_property_names.add(name) functions.extend([value.fget, value.fset, value.fdel]) # may contain Nones value = abstractproperty(value.fget, value.fset, value.fdel) else: raise ValueError( 'Interface class attributes must have a value of None\n{}={}'. format(name, value)) namespace[name] = value return namespace, functions, interface_method_signatures, interface_property_names, interface_attribute_names
def compatibleabstractproperty(func): """ Python 2 and python 3 differ in decorator for abstract property. in python 3 (gt 3.3) it is: @property @abstractproperty in python 2 @abstractproperty """ if PY2: # pylint: disable=no-else-return return abstractproperty(func) else: return property(abstractmethod(func))
class Operation(object): __metaclass__ = ABCMeta execute = abstractmethod(lambda self: None) def update_cache(self): pass @property def collection(self): return self.session.db[self.type.get_collection_name()] def ensure_indexes(self): self.session.auto_ensure_indexes(self.type)
class RegistrationForm(forms.Form): """ Basic registration form class requiring only a valid email. This class is not supposed to be used directly but subclasses implementing ``clean_email`` method. There is no requirement on using this as base class. """ email = forms.EmailField(widget=forms.TextInput( attrs=dict(attrs_dict, maxlength=75))) def clean_email(self): pass clean_email = abc.abstractmethod(clean_email)
def generate_abstract_class(class_naming: NamedProperty): """ >>> cl = PropertyList() >>> cl.add(Naming("distance")) >>> cl.add(Naming("duration")) >>> c = NamedProperty(Naming("speed"), cl) >>> ISpeed = InterfaceGenerator.generate_abstract_class(c) >>> import types >>> class Speed(ISpeed, types.SimpleNamespace): ... def __init__(self, distance, duration): ... super().__init__(distance=distance, duration=duration) >>> s = Speed(1,2) >>> s Speed(distance=1, duration=2) >>> class Speed(ISpeed): ... def __init__(self): ... super().__init__() >>> s = Speed() Traceback (most recent call last): ... TypeError: Can't instantiate abstract class Speed with abstract methods distance, duration """ template = InterfaceGenerator.get_class_template(class_naming.naming) getters = set() for sub_property_naming in class_naming.properties: getters.add(sub_property_naming.value_name) def getter(self): raise NotImplementedError( "Getter for property {} is not impplemented".format( sub_property_naming.value_name)) getter.__name__ = sub_property_naming.value_name getter = abstractmethod(getter) setattr(template, sub_property_naming.value_name, getter) doc_str = "The {} of the {} instance.".format( sub_property_naming.docstring_name, class_naming.naming.docstring_name) p = property(fget=getter, doc=doc_str) setattr(template, sub_property_naming.value_name, p) template.__abstractmethods__ = frozenset(getters) return template
def decorator(function): assert isfunction(function), 'Invalid function %s' % function nonlocal method name = function.__name__ if method is None: for regex, m in NAME_TO_METHOD.items(): if match(regex, name): method = m break else: raise DevelError('Cannot deduce method for function name "%s"' % name) output, inputs = extractOuputInput(function, types, modelToId=method in (GET, DELETE)) function._ally_call = Call(name, method, output, inputs, hints) return abstractmethod(function)
def test_abstract_subclasses(self): AbstractSubclass = ABCMeta( 'AbstractSubclass', (greenlet,), {'run': abstractmethod(lambda self: None)}) class BadSubclass(AbstractSubclass): pass class GoodSubclass(AbstractSubclass): def run(self): pass GoodSubclass() # should not raise self.assertRaises(TypeError, BadSubclass)
def interface(obj): """Decorator""" if not isinstance(obj, type(OOPMeta)): return obj; absMethods = set(); for name, method in obj.__dict__.items(): if inspect.isfunction(method): absMethods.add(name); setattr(obj, name, abc.abstractmethod(method)); obj.__interfacemethods__ = frozenset(absMethods); return abstractclass(obj);
class abc: def my(self): return "shreyansh" @classmethod def mn(cls): return "sinha" @staticmethod def mz(): return "chotu" abc.abstractmethod() def bc(self): pass
def abstractclass(cls): name = cls.__name__ bases = cls.__bases__ mdict = cls.__dict__ absdict = { } for mname, method in mdict.items(): if isinstance(method, types.FunctionType): absdict[mname] = abc.abstractmethod(method) else: absdict[mname] = method abclass = type(name, bases, absdict) abclass return abclass
def decorator(function): assert isfunction(function), 'Invalid function %s' % function nonlocal method name = function.__name__ if method is None: for regex, m in NAME_TO_METHOD.items(): if match(regex, name): method = m break else: raise DevelError( 'Cannot deduce method for function name "%s"' % name) output, inputs = extractOuputInput(function, types, modelToId=method in (GET, DELETE)) function._ally_call = Call(name, method, output, inputs, hints) return abstractmethod(function)
class ActivationForm(forms.Form): """ Basic activation form class requiring only a password. This class is not supposed to be used directly but subclasses implementing at least ``clean`` method (**note**: there is no check on password value, unless you provide a clean_password1 method). There is no requirement on using this as base class. """ password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (again)")) def clean(self): pass clean = abc.abstractmethod(clean)
validator.message(obj, name=name) ) return obj interface = abc.abstractproperty(_NOT_IMPLEMENTED) # type: InterfaceType invoke = abc.abstractproperty(_NOT_IMPLEMENTED) # type: Callable[[AnyArgs], Any] exception = abc.abstractproperty(_NOT_IMPLEMENTED) # type: Exception message = abc.abstractmethod(_NOT_IMPLEMENTED) # type: Callable[[AnyArgs], Any] class AssertInterface(GenericFunctionInterface): pass class Assert(GenericFunction): inter class Validate(): def __new__(cls, *args, **kwargs):
def required(fun): return abc.abstractmethod(fun)
def __init__(self, project_name): self.__pm = PluginManager(project_name) self.__add_spec = HookspecMarker(project_name) self.__add_abcspec = lambda *args, **kwargs: abc.abstractmethod( self.__add_spec(*args, **kwargs)) self.__add_hook = HookimplMarker(project_name)
with mock.patch('glob.glob', side_effect=(files[:1], files[1:], [])) as mocked: assert files == utils.find_req_files(root) assert mocked.call_args_list == [mock.call(target) for target in targets] # Test it returns what we expect when just one pattern finds something with mock.patch('glob.glob', side_effect=(files, [], [])) as mocked: assert files == utils.find_req_files(root) assert mocked.call_args_list == [mock.call(target) for target in targets] # Test it returns empty list if not reqfile is found with mock.patch('glob.glob', side_effect=([], [], [])) as mocked: assert [] == utils.find_req_files(root) assert mocked.call_args_list == [mock.call(target) for target in targets] Meta = utils.PluginMount('Meta', (object,), {'test': abc.abstractmethod(lambda x: x)}) def test_plugin_mount(): '''Tests PluginMount metaclass''' assert 0 == len(Meta.plugins) with pytest.raises(TypeError): class A(Meta): pass A() assert 1 == len(Meta.plugins) class B(Meta): def test(self, value): return value assert 2 == len(Meta.plugins)
class B(SomeInterface): def f(self): super(B, self).f() # Абстрактный метод вызывается через super def g(self): SomeInterface.g(self) # Абстрактный метод вызывается напрямую b = B() b.f() # SomeInterface.f() b.g() # SomeInterface.g() # Абстрактные методы можно создавать только в описании класса. Если добавить # абстрактный метод позже, он не будет учтен, потому что список абстрактных # методов составляется при создании класса. SomeInterface.h = abc.abstractmethod(lambda: 123) class C(B): pass c = C() # Никакой ошибки, т.к. все абстрактные методы класса # SomeInterface были обнаружены в момент его создания. # Хотя h фактически является абстрактным. # Функции isinstance(экземпляр, класс) и issubclass(подкласс, класс) вызывают # методы класс.__instancecheck__(экземпляр) и класс.__subclasscheck__(подкласс). # Для ABCMeta эти методы проверяют классы, зарегистрированные через # ABCMeta.register(). При необходимости можно переопределить эти методы, но # удобнее переопределить ABCMeta.__subclasshook__(подкласс). Он вызывается из # __subclasscheck__() и должен возвращать или True, или False, или # NotImplemented (в последнем случае проверка будет делаться как обычно).
else: self.logger.debug("NOT base64 decoding message") deserialized = self.deserialize(msg) self.logger.debug("deserialized message: {d}".format(d=deserialized)) return self.verify(deserialized) def sign(self, msg): """Signs the given message using provided security method. :arg pymco.message.Message msg: message to be signed. :return: signed message. """ def verify(self, msg): """Verify the given message using provided security method. :arg pymco.message.Message msg: message to be verified. :return: verified message. :raise pymco.exc.MessageVerificationError: If the message verification failed. """ # Building Metaclass here for Python 2/3 compatibility SecurityProvider = abc.ABCMeta('SecurityProvider', (SecurityProviderBase,), { 'sign': abc.abstractmethod(sign), 'verify': abc.abstractmethod(verify), })
from abc import ABCMeta from abc import abstractmethod ABCMeta() abstractmethod() class NewParent(metaclass=ABCMeta): @classmethod @abstractmethod def foo_method(cls): pass
def attribute(func): """Wrap a function as an attribute.""" attr = abc.abstractmethod(func) attr.__iattribute__ = True attr = _property(attr) return attr
:arg pymco.message.Message msg: Message to be serialized. :return: Decoded message, a :py:class:`dict` like object. """ return self.verify(self.deserialize(msg)) def sign(self, msg): """Signs the given message using provided security method. :arg pymco.message.Message msg: message to be signed. :return: signed message. """ def verify(self, msg): """Verify the given message using provided security method. :arg pymco.message.Message msg: message to be verified. :return: verified message. :raise pymco.exc.MessageVerificationError: If the message verification failed. """ # Building Metaclass here for Python 2/3 compatibility SecurityProvider = abc.ABCMeta( "SecurityProvider", (SecurityProviderBase,), {"sign": abc.abstractmethod(sign), "verify": abc.abstractmethod(verify)}, )
return connect.StompConnection11(try_loopback_connect=False, **params) def get_target(self, agent, collective, topciprefix=None): """Get the message target for the given agent and collective. :arg agent: MCollective target agent name. :arg collective: MCollective target collective. :arg topicprefix: Required for older versions of MCollective :return: Message target string representation for given agent and collective. """ def get_reply_target(self, agent, collective): """Get the message target for the given agent and collective. :arg agent: MCollective target agent name. :arg collective: MCollective target collective. :return: message reply target string representation for given agent and collective. """ # Building Metaclass here for Python 2/3 compatibility Connector = abc.ABCMeta('Connector', (BaseConnector,), { 'get_target': abc.abstractmethod(get_target), 'get_reply_target': abc.abstractmethod(get_reply_target), })
def method(func): """Wrap a function as a method.""" attr = abc.abstractmethod(func) attr.__imethod__ = True return attr
---------------- pymco Message [de]serialization. """ import abc def serialize(self, msg): """Serialize a MCollective msg. :arg msg: message to be serialized. :return: serialized message. """ def deserialize(self, msg): """De-serialize a MCollective msg. :arg pymco.message.Message msg: message to be de-serialized. :return: de-serialized message. """ # Building Metaclass here for Python 2/3 compatibility SerializerBase = abc.ABCMeta('SerializerBase', (object,), { '__doc__': 'Base class for all serializers.', 'serialize': abc.abstractmethod(serialize), 'deserialize': abc.abstractmethod(deserialize), 'plugins': { 'yaml': 'pymco.serializers.yaml.Serializer', } })
def abstractproperty(func): return property(abstractmethod(func))
def _abstractmethod(func=_nonfunc): return abc.abstractmethod(func)
def __init__(self, func): func = abc.abstractmethod(func) super(abstractclassmethod, self).__init__(func)
for plugin in Classifier.plugins: keyword = plugin().check(filename) if keyword: return keyword # Metaclass trick to get python2/3 compat. Abstract methods must be defined # into the mataclass instead of the base classes, so that ABCMeta can do it's # magic. See http://goo.gl/azOTtq for further information about metaclasses in # Python 2 and Python 3. Classifier = utils.PluginMount('Classifier', (BaseClassifier,), { '__doc__': BaseClassifier.__doc__, 'classify': staticmethod(classify), 'check': abc.abstractmethod(check), }) class RegexClassifierMixin(object): """Provide regex based classifcation.""" regex = None def get_regex(self): if not self.regex: raise ValueError return self.regex def check(self, filename): match = self.get_regex().match(filename) if match: