我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用abc.abstractproperty()。
def verify_interface(iface, klass): for method in iface.__abstractmethods__: if not hasattr(klass, method): raise InterfaceNotImplemented( "{0} is missing a {1!r} method".format(klass, method) ) if isinstance(getattr(iface, method), abc.abstractproperty): # Can't properly verify these yet. continue sig = signature(getattr(iface, method)) actual = signature(getattr(klass, method)) if sig != actual: raise InterfaceNotImplemented( "{0}.{1}'s signature differs from the expected. Expected: " "{2!r}. Received: {3!r}".format( klass, method, sig, actual ) )
def verify_interface(iface, klass): for method in iface.__abstractmethods__: if not hasattr(klass, method): raise InterfaceNotImplemented( "{0} is missing a {1!r} method".format(klass, method) ) if isinstance(getattr(iface, method), abc.abstractproperty): # Can't properly verify these yet. continue spec = inspect.getargspec(getattr(iface, method)) actual = inspect.getargspec(getattr(klass, method)) if spec != actual: raise InterfaceNotImplemented( "{0}.{1}'s signature differs from the expected. Expected: " "{2!r}. Received: {3!r}".format( klass, method, spec, actual ) )
def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C(metaclass=abc.ABCMeta): @abc.abstractproperty def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @property def foo(self): return super().foo self.assertEqual(D().foo, 3) self.assertFalse(getattr(D.foo, "__isabstractmethod__", False))
def _patch_properties(cls, base_abstract_properties): """ Create an AttributeProperty for interface properties not provided by an implementation. """ abstract_properties = set() functions = [] for attr in cls.__abstractmethods__: value = getattr(cls, attr) if isinstance(value, abstractproperty): functions.extend([value.fget, value.fset, value.fdel]) # may contain Nones setattr(cls, attr, AttributeProperty(attr)) abstract_properties.add(attr) cls._pi.abstractproperties = frozenset(abstract_properties | base_abstract_properties) abstractmethods = set(cls.__abstractmethods__) - abstract_properties for func in functions: if func is not None and func.__name__ in abstractmethods: abstractmethods.discard(func.__name__) cls.__abstractmethods__ = frozenset(abstractmethods)
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)
def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C(metaclass=abc.ABCMeta): @abc.abstractproperty def foo(self): return 3 class D(C): @property def foo(self): return super().foo self.assertEqual(D().foo, 3)
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc.ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C: __metaclass__ = abc.ABCMeta @abc.abstractproperty def foo(self): return 3 class D(C): @property def foo(self): return super(D, self).foo self.assertEqual(D().foo, 3)
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty]: class C: __metaclass__ = abc.ABCMeta @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, set(["bar"])) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def abstractmethod(func): return func # def abstractproperty(): # return None
def lazy_abstractproperty(function): """A lazy abstractproperty that is only evaluated once. Reduces clutter code and is similar to a singleton implementation for a property. References: http://danijar.com/structuring-your-tensorflow-models/ """ attribute = '_' + function.__name__ @abstractproperty @functools.wraps(function) def wrapper(self): if not hasattr(self, attribute): setattr(self, attribute, function(self)) return getattr(self, attribute) return wrapper
def test_interface_abc_detection(self): @six.add_metaclass(abc.ABCMeta) class IABC(object): @abc.abstractmethod def foo(self): pass @abc.abstractproperty def bar(self): return None class EmptyABCPI(IABC, pure_interface.PureInterface): pass class PIEmptyABC(pure_interface.PureInterface, IABC): pass self.assertTrue(EmptyABCPI._pi.type_is_pure_interface) self.assertTrue(PIEmptyABC._pi.type_is_pure_interface) if six.PY3: self.assertTrue('foo' in EmptyABCPI._pi.interface_method_names) self.assertTrue('bar' in EmptyABCPI._pi.interface_property_names) self.assertTrue('foo' in PIEmptyABC._pi.interface_method_names) self.assertTrue('bar' in PIEmptyABC._pi.interface_property_names) with self.assertRaises(TypeError): EmptyABCPI() with self.assertRaises(TypeError): PIEmptyABC()
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() for name, value in six.iteritems(attributes): if _builtin_attrs(name): pass # shortcut 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] = _get_function_signature(func) elif isinstance(value, property): interface_property_names.add(name) elif isinstance(value, staticmethod): func = value.__func__ functions.append(func) interface_method_signatures[name] = _get_function_signature(func) value = abstractstaticmethod(func) elif isinstance(value, classmethod): func = value.__func__ interface_method_signatures[name] = _get_function_signature(func) functions.append(func) value = abstractclassmethod(func) elif isinstance(value, types.FunctionType): functions.append(value) interface_method_signatures[name] = _get_function_signature(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) namespace[name] = value return namespace, functions, interface_method_signatures, interface_property_names
def _abstract_readwrite_property(**kwds): p = abc.abstractproperty(fget=_not_implemented, fset=_not_implemented, **kwds) if 'doc' in kwds: p.__doc__ = kwds['doc'] return p
def _abstract_readonly_property(**kwds): p = abc.abstractproperty(fget=_not_implemented, **kwds) if 'doc' in kwds: p.__doc__ = kwds['doc'] return p
def code_size(self): """Return the size of each code. This number is a constant and should agree with the output of the `encode` op (e.g. if rel_codes is the output of self.encode(...), then it should have shape [N, code_size()]). This abstractproperty should be overridden by implementations. Returns: an integer constant """ pass