Python abc.ABCMeta() Examples

The following are 30 code examples for showing how to use abc.ABCMeta(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module abc , or try the search function .

Example 1
Project: picoCTF   Author: picoCTF   File: deploy.py    License: MIT License 6 votes vote down vote up
def challenge_meta(attributes):
    """
    Returns a metaclass that will introduce the given attributes into the class
    namespace.

    Args:
        attributes: The dictionary of attributes

    Returns:
        The metaclass described above
    """

    class ChallengeMeta(ABCMeta):
        def __new__(cls, name, bases, attr):
            attrs = dict(attr)
            attrs.update(attributes)
            return super().__new__(cls, name, bases, attrs)

    return ChallengeMeta 
Example 2
Project: ironpython2   Author: IronLanguages   File: test_descr.py    License: Apache License 2.0 6 votes vote down vote up
def test_slots_descriptor(self):
        # Issue2115: slot descriptors did not correctly check
        # the type of the given object
        import abc
        class MyABC:
            __metaclass__ = abc.ABCMeta
            __slots__ = "a"

        class Unrelated(object):
            pass
        MyABC.register(Unrelated)

        u = Unrelated()
        self.assertIsInstance(u, MyABC)

        # This used to crash
        self.assertRaises(TypeError, MyABC.a.__set__, u, 3) 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_abc.py    License: Apache License 2.0 6 votes vote down vote up
def test_registration_basics(self):
        class A:
            __metaclass__ = abc.ABCMeta
        class B(object):
            pass
        b = B()
        self.assertFalse(issubclass(B, A))
        self.assertFalse(issubclass(B, (A,)))
        self.assertNotIsInstance(b, A)
        self.assertNotIsInstance(b, (A,))
        A.register(B)
        self.assertTrue(issubclass(B, A))
        self.assertTrue(issubclass(B, (A,)))
        self.assertIsInstance(b, A)
        self.assertIsInstance(b, (A,))
        class C(B):
            pass
        c = C()
        self.assertTrue(issubclass(C, A))
        self.assertTrue(issubclass(C, (A,)))
        self.assertIsInstance(c, A)
        self.assertIsInstance(c, (A,)) 
Example 4
Project: ironpython2   Author: IronLanguages   File: test_abc.py    License: Apache License 2.0 6 votes vote down vote up
def test_registration_edge_cases(self):
        class A:
            __metaclass__ = abc.ABCMeta
        A.register(A)  # should pass silently
        class A1(A):
            pass
        self.assertRaises(RuntimeError, A1.register, A)  # cycles not allowed
        class B(object):
            pass
        A1.register(B)  # ok
        A1.register(B)  # should pass silently
        class C(A):
            pass
        A.register(C)  # should pass silently
        self.assertRaises(RuntimeError, C.register, A)  # cycles not allowed
        C.register(B)  # ok 
Example 5
Project: ironpython2   Author: IronLanguages   File: test_abc.py    License: Apache License 2.0 6 votes vote down vote up
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None) 
Example 6
Project: BinderFilter   Author: dxwu   File: test_descr.py    License: MIT License 6 votes vote down vote up
def test_slots_descriptor(self):
        # Issue2115: slot descriptors did not correctly check
        # the type of the given object
        import abc
        class MyABC:
            __metaclass__ = abc.ABCMeta
            __slots__ = "a"

        class Unrelated(object):
            pass
        MyABC.register(Unrelated)

        u = Unrelated()
        self.assertIsInstance(u, MyABC)

        # This used to crash
        self.assertRaises(TypeError, MyABC.a.__set__, u, 3) 
Example 7
Project: BinderFilter   Author: dxwu   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_registration_basics(self):
        class A:
            __metaclass__ = abc.ABCMeta
        class B(object):
            pass
        b = B()
        self.assertFalse(issubclass(B, A))
        self.assertFalse(issubclass(B, (A,)))
        self.assertNotIsInstance(b, A)
        self.assertNotIsInstance(b, (A,))
        A.register(B)
        self.assertTrue(issubclass(B, A))
        self.assertTrue(issubclass(B, (A,)))
        self.assertIsInstance(b, A)
        self.assertIsInstance(b, (A,))
        class C(B):
            pass
        c = C()
        self.assertTrue(issubclass(C, A))
        self.assertTrue(issubclass(C, (A,)))
        self.assertIsInstance(c, A)
        self.assertIsInstance(c, (A,)) 
Example 8
Project: BinderFilter   Author: dxwu   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_registration_edge_cases(self):
        class A:
            __metaclass__ = abc.ABCMeta
        A.register(A)  # should pass silently
        class A1(A):
            pass
        self.assertRaises(RuntimeError, A1.register, A)  # cycles not allowed
        class B(object):
            pass
        A1.register(B)  # ok
        A1.register(B)  # should pass silently
        class C(A):
            pass
        A.register(C)  # should pass silently
        self.assertRaises(RuntimeError, C.register, A)  # cycles not allowed
        C.register(B)  # ok 
Example 9
Project: BinderFilter   Author: dxwu   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None) 
Example 10
Project: dimod   Author: dwavesystems   File: meta.py    License: Apache License 2.0 6 votes vote down vote up
def __new__(mcls, name, bases, namespace, **kwargs):
        cls = abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)

        samplermixins = {name
                         for name, value in namespace.items()
                         if getattr(value, "__issamplemixin__", False)}
        if len(samplermixins) == 3:
            abstracts = samplermixins
        else:
            abstracts = set()

        for base in bases:
            samplermixins = {name
                             for name in getattr(base, "__abstractmethods__", set())
                             if getattr(getattr(cls, name, None), "__issamplemixin__", False)}
            if len(samplermixins) == 3:
                abstracts.update(samplermixins)

        # if we found any, update abstract methods
        if abstracts:
            cls.__abstractmethods__ = frozenset(abstracts.union(cls.__abstractmethods__))

        return cls 
Example 11
Project: oss-ftp   Author: aliyun   File: test_descr.py    License: MIT License 6 votes vote down vote up
def test_slots_descriptor(self):
        # Issue2115: slot descriptors did not correctly check
        # the type of the given object
        import abc
        class MyABC:
            __metaclass__ = abc.ABCMeta
            __slots__ = "a"

        class Unrelated(object):
            pass
        MyABC.register(Unrelated)

        u = Unrelated()
        self.assertIsInstance(u, MyABC)

        # This used to crash
        self.assertRaises(TypeError, MyABC.a.__set__, u, 3) 
Example 12
Project: oss-ftp   Author: aliyun   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_registration_basics(self):
        class A:
            __metaclass__ = abc.ABCMeta
        class B(object):
            pass
        b = B()
        self.assertFalse(issubclass(B, A))
        self.assertFalse(issubclass(B, (A,)))
        self.assertNotIsInstance(b, A)
        self.assertNotIsInstance(b, (A,))
        A.register(B)
        self.assertTrue(issubclass(B, A))
        self.assertTrue(issubclass(B, (A,)))
        self.assertIsInstance(b, A)
        self.assertIsInstance(b, (A,))
        class C(B):
            pass
        c = C()
        self.assertTrue(issubclass(C, A))
        self.assertTrue(issubclass(C, (A,)))
        self.assertIsInstance(c, A)
        self.assertIsInstance(c, (A,)) 
Example 13
Project: oss-ftp   Author: aliyun   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_registration_edge_cases(self):
        class A:
            __metaclass__ = abc.ABCMeta
        A.register(A)  # should pass silently
        class A1(A):
            pass
        self.assertRaises(RuntimeError, A1.register, A)  # cycles not allowed
        class B(object):
            pass
        A1.register(B)  # ok
        A1.register(B)  # should pass silently
        class C(A):
            pass
        A.register(C)  # should pass silently
        self.assertRaises(RuntimeError, C.register, A)  # cycles not allowed
        C.register(B)  # ok 
Example 14
Project: oss-ftp   Author: aliyun   File: test_abc.py    License: MIT License 6 votes vote down vote up
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None) 
Example 15
Project: blueoil   Author: blue-oil   File: config.py    License: Apache License 2.0 6 votes vote down vote up
def _save_config_yaml(output_dir, config):
    file_name = 'config.yaml'
    config_dict = _easy_dict_to_dict(config)
    file_path = os.path.join(output_dir, file_name)

    class Dumper(yaml.Dumper):
        def ignore_aliases(self, data):
            return True
    Dumper.add_representer(ABCMeta, Representer.represent_name)

    if type(config_dict['CLASSES']) != list:
        DatasetClass = config.DATASET_CLASS
        dataset_kwargs = dict((key.lower(), val) for key, val in config.DATASET.items())
        train_dataset = DatasetClass(
            subset="train",
            **dataset_kwargs,
        )
        config_dict['CLASSES'] = train_dataset.classes

    with gfile.GFile(os.path.join(output_dir, file_name), 'w') as outfile:
        yaml.dump(config_dict, outfile, default_flow_style=False, Dumper=Dumper)

    return file_path 
Example 16
Project: blueoil   Author: blue-oil   File: config.py    License: Apache License 2.0 6 votes vote down vote up
def _save_config_yaml(output_dir, config):
    file_name = 'config.yaml'
    config_dict = _easy_dict_to_dict(config)
    file_path = os.path.join(output_dir, file_name)

    class Dumper(yaml.Dumper):
        def ignore_aliases(self, data):
            return True
    Dumper.add_representer(ABCMeta, Representer.represent_name)

    if type(config_dict['CLASSES']) != list:
        DatasetClass = config.DATASET_CLASS
        dataset_kwargs = dict((key.lower(), val) for key, val in config.DATASET.items())
        train_dataset = DatasetClass(
            subset="train",
            **dataset_kwargs,
        )
        config_dict['CLASSES'] = train_dataset.classes

    with gfile.GFile(os.path.join(output_dir, file_name), 'w') as outfile:
        yaml.dump(config_dict, outfile, default_flow_style=False, Dumper=Dumper)

    return file_path 
Example 17
Project: Fluid-Designer   Author: Microvellum   File: test_descr.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_slots_descriptor(self):
        # Issue2115: slot descriptors did not correctly check
        # the type of the given object
        import abc
        class MyABC(metaclass=abc.ABCMeta):
            __slots__ = "a"

        class Unrelated(object):
            pass
        MyABC.register(Unrelated)

        u = Unrelated()
        self.assertIsInstance(u, MyABC)

        # This used to crash
        self.assertRaises(TypeError, MyABC.a.__set__, u, 3) 
Example 18
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example 19
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_abstractclassmethod_basics(self):
        @abc.abstractclassmethod
        def foo(cls): pass
        self.assertTrue(foo.__isabstractmethod__)
        @classmethod
        def bar(cls): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @abc.abstractclassmethod
            def foo(cls): return cls.__name__
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
        self.assertEqual(D().foo(), 'D') 
Example 20
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_abstractproperty_basics(self):
        @property
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertEqual(D().foo, 3) 
Example 21
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_abstractclassmethod_basics(self):
        @classmethod
        @abc.abstractmethod
        def foo(cls): pass
        self.assertTrue(foo.__isabstractmethod__)
        @classmethod
        def bar(cls): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
        self.assertEqual(D().foo(), 'D') 
Example 22
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_abstractstaticmethod_basics(self):
        @staticmethod
        @abc.abstractmethod
        def foo(): pass
        self.assertTrue(foo.__isabstractmethod__)
        @staticmethod
        def bar(): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @staticmethod
            @abc.abstractmethod
            def foo(): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @staticmethod
            def foo(): return 4
        self.assertEqual(D.foo(), 4)
        self.assertEqual(D().foo(), 4) 
Example 23
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_registration_basics(self):
        class A(metaclass=abc.ABCMeta):
            pass
        class B(object):
            pass
        b = B()
        self.assertFalse(issubclass(B, A))
        self.assertFalse(issubclass(B, (A,)))
        self.assertNotIsInstance(b, A)
        self.assertNotIsInstance(b, (A,))
        B1 = A.register(B)
        self.assertTrue(issubclass(B, A))
        self.assertTrue(issubclass(B, (A,)))
        self.assertIsInstance(b, A)
        self.assertIsInstance(b, (A,))
        self.assertIs(B1, B)
        class C(B):
            pass
        c = C()
        self.assertTrue(issubclass(C, A))
        self.assertTrue(issubclass(C, (A,)))
        self.assertIsInstance(c, A)
        self.assertIsInstance(c, (A,)) 
Example 24
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_register_as_class_deco(self):
        class A(metaclass=abc.ABCMeta):
            pass
        @A.register
        class B(object):
            pass
        b = B()
        self.assertTrue(issubclass(B, A))
        self.assertTrue(issubclass(B, (A,)))
        self.assertIsInstance(b, A)
        self.assertIsInstance(b, (A,))
        @A.register
        class C(B):
            pass
        c = C()
        self.assertTrue(issubclass(C, A))
        self.assertTrue(issubclass(C, (A,)))
        self.assertIsInstance(c, A)
        self.assertIsInstance(c, (A,))
        self.assertIs(C, A.register(C)) 
Example 25
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_registration_edge_cases(self):
        class A(metaclass=abc.ABCMeta):
            pass
        A.register(A)  # should pass silently
        class A1(A):
            pass
        self.assertRaises(RuntimeError, A1.register, A)  # cycles not allowed
        class B(object):
            pass
        A1.register(B)  # ok
        A1.register(B)  # should pass silently
        class C(A):
            pass
        A.register(C)  # should pass silently
        self.assertRaises(RuntimeError, C.register, A)  # cycles not allowed
        C.register(B)  # ok 
Example 26
Project: Fluid-Designer   Author: Microvellum   File: test_inspect.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_isabstract(self):
        from abc import ABCMeta, abstractmethod

        class AbstractClassExample(metaclass=ABCMeta):

            @abstractmethod
            def foo(self):
                pass

        class ClassExample(AbstractClassExample):
            def foo(self):
                pass

        a = ClassExample()

        # Test general behaviour.
        self.assertTrue(inspect.isabstract(AbstractClassExample))
        self.assertFalse(inspect.isabstract(ClassExample))
        self.assertFalse(inspect.isabstract(a))
        self.assertFalse(inspect.isabstract(int))
        self.assertFalse(inspect.isabstract(5)) 
Example 27
Project: Imogen   Author: CedricGuillemet   File: inspect.py    License: MIT License 6 votes vote down vote up
def isabstract(object):
    """Return true if the object is an abstract base class (ABC)."""
    if not isinstance(object, type):
        return False
    if object.__flags__ & TPFLAGS_IS_ABSTRACT:
        return True
    if not issubclass(type(object), abc.ABCMeta):
        return False
    if hasattr(object, '__abstractmethods__'):
        # It looks like ABCMeta.__new__ has finished running;
        # TPFLAGS_IS_ABSTRACT should have been accurate.
        return False
    # It looks like ABCMeta.__new__ has not finished running yet; we're
    # probably in __init_subclass__. We'll look for abstractmethods manually.
    for name, value in object.__dict__.items():
        if getattr(value, "__isabstractmethod__", False):
            return True
    for base in object.__bases__:
        for name in getattr(base, "__abstractmethods__", ()):
            value = getattr(object, name, None)
            if getattr(value, "__isabstractmethod__", False):
                return True
    return False 
Example 28
Project: python-clean-architecture   Author: pcah   File: test_functools.py    License: MIT License 5 votes vote down vote up
def test_abstractmethod_register(self):
        class Abstract(abc.ABCMeta):

            @singledispatchmethod
            @abc.abstractmethod
            def add(self, x, y):
                pass

        assert Abstract.add.__isabstractmethod__ is True 
Example 29
Project: jawfish   Author: war-and-code   File: _abcoll.py    License: MIT License 5 votes vote down vote up
def abstractmethod(self):
    return self

### ONE-TRICK PONIES ###


#class Iterable(metaclass=ABCMeta): 
Example 30
Project: jawfish   Author: war-and-code   File: _abcoll.py    License: MIT License 5 votes vote down vote up
def __subclasshook__(cls, C):
        if cls is Iterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented


#class Sized(metaclass=ABCMeta):