Python abc.abstractmethod() Examples

The following are 30 code examples of abc.abstractmethod(). 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 also want to check out all available functions/classes of the module abc , or try the search function .
Example #1
Source File: test_check_docs.py    From python-netsurv with MIT License 7 votes vote down vote up
def test_ignores_return_in_abstract_method_sphinx(self):
        """Example of an abstract method documenting the return type that an
        implementation should return.
        """
        node = astroid.extract_node("""
        import abc
        class Foo(object):
            @abc.abstractmethod
            def foo(self): #@
                '''docstring ...

                :returns: Ten
                :rtype: int
                '''
                return 10
        """)
        with self.assertNoMessages():
            self.checker.visit_functiondef(node) 
Example #2
Source File: test_check_docs.py    From python-netsurv with MIT License 7 votes vote down vote up
def test_ignores_return_in_abstract_method_google(self):
        """Example of an abstract method documenting the return type that an
        implementation should return.
        """
        node = astroid.extract_node("""
        import abc
        class Foo(object):
            @abc.abstractmethod
            def foo(self): #@
                '''docstring ...

                Returns:
                    int: Ten
                '''
                return 10
        """)
        with self.assertNoMessages():
            self.checker.visit_functiondef(node) 
Example #3
Source File: test_abc.py    From BinderFilter with 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 #4
Source File: test_check_docs.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_ignores_return_in_abstract_method_numpy(self):
        """Example of an abstract method documenting the return type that an
        implementation should return.
        """
        node = astroid.extract_node("""
        import abc
        class Foo(object):
            @abc.abstractmethod
            def foo(self): #@
                '''docstring ...

                Returns
                -------
                int
                    Ten
                '''
                return 10
        """)
        with self.assertNoMessages():
            self.checker.visit_functiondef(node) 
Example #5
Source File: test_check_docs.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_ignores_return_in_abstract_method_sphinx(self):
        """Example of an abstract method documenting the return type that an
        implementation should return.
        """
        node = astroid.extract_node("""
        import abc
        class Foo(object):
            @abc.abstractmethod
            def foo(self): #@
                '''docstring ...

                :returns: Ten
                :rtype: int
                '''
                return 10
        """)
        with self.assertNoMessages():
            self.checker.visit_functiondef(node) 
Example #6
Source File: test_check_docs.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_ignores_return_in_abstract_method_google(self):
        """Example of an abstract method documenting the return type that an
        implementation should return.
        """
        node = astroid.extract_node("""
        import abc
        class Foo(object):
            @abc.abstractmethod
            def foo(self): #@
                '''docstring ...

                Returns:
                    int: Ten
                '''
                return 10
        """)
        with self.assertNoMessages():
            self.checker.visit_functiondef(node) 
Example #7
Source File: test_abc.py    From Project-New-Reign---Nemesis-Main with 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 #8
Source File: test_abc.py    From ironpython3 with Apache License 2.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 #9
Source File: test_inheritance_postcondition.py    From icontract with MIT License 6 votes vote down vote up
def test_abstract_method(self) -> None:
        class A(icontract.DBC):
            @icontract.ensure(lambda result: result < 100)
            @abc.abstractmethod
            def func(self) -> int:
                pass

        class B(A):
            def func(self) -> int:
                return 1000

        b = B()
        violation_error = None  # type: Optional[icontract.ViolationError]
        try:
            b.func()
        except icontract.ViolationError as err:
            violation_error = err

        self.assertIsNotNone(violation_error)
        self.assertEqual("result < 100: result was 1000", tests.error.wo_mandatory_location(str(violation_error))) 
Example #10
Source File: test_abc.py    From Project-New-Reign---Nemesis-Main with 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 #11
Source File: test_abc.py    From ironpython2 with 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 #12
Source File: test_inheritance_postcondition.py    From icontract with MIT License 6 votes vote down vote up
def test_abstract_method_not_implemented(self) -> None:
        # pylint: disable=abstract-method
        class A(icontract.DBC):
            @icontract.ensure(lambda result: result < 100)
            @abc.abstractmethod
            def func(self) -> int:
                pass

        class B(A):
            pass

        type_err = None  # type: Optional[TypeError]
        try:
            _ = B()  # type: ignore
        except TypeError as err:
            type_err = err

        self.assertIsNotNone(type_err)
        self.assertEqual("Can't instantiate abstract class B with abstract methods func", str(type_err)) 
Example #13
Source File: test_inheritance_precondition.py    From icontract with MIT License 6 votes vote down vote up
def test_abstract_method(self) -> None:
        class A(icontract.DBC):
            @icontract.require(lambda x: x > 0)
            @abc.abstractmethod
            def func(self, x: int) -> int:
                pass

        class B(A):
            def func(self, x: int) -> int:
                return 1000

        b = B()
        violation_error = None  # type: Optional[icontract.ViolationError]
        try:
            b.func(x=-1)
        except icontract.ViolationError as err:
            violation_error = err

        self.assertIsNotNone(violation_error)
        self.assertEqual("x > 0: x was -1", tests.error.wo_mandatory_location(str(violation_error))) 
Example #14
Source File: test_abc.py    From ironpython3 with Apache License 2.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 #15
Source File: test_postcondition.py    From icontract with MIT License 6 votes vote down vote up
def test_postcondition_in_abstract_class_method(self) -> None:
        class Abstract(icontract.DBC):
            @classmethod
            @abc.abstractmethod
            @icontract.ensure(lambda result: result != 0)
            def some_func(cls: Type['Abstract'], x: int) -> int:
                pass

        class SomeClass(Abstract):
            @classmethod
            def some_func(cls: Type['SomeClass'], x: int) -> int:
                return x

        result = SomeClass.some_func(x=1)
        self.assertEqual(1, result)

        violation_error = None  # type: Optional[icontract.ViolationError]
        try:
            _ = SomeClass.some_func(x=0)
        except icontract.ViolationError as err:
            violation_error = err

        self.assertIsNotNone(violation_error)
        self.assertEqual('result != 0: result was 0', tests.error.wo_mandatory_location(str(violation_error))) 
Example #16
Source File: test_functools.py    From python-clean-architecture with MIT License 6 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 #17
Source File: test_abc.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #18
Source File: test_final.py    From zipline-chinese with Apache License 2.0 6 votes vote down vote up
def setUpClass(cls):
        FinalABCMeta = final_meta_factory(ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal 
Example #19
Source File: test_abc.py    From oss-ftp with 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 #20
Source File: meta_base_algorithm.py    From rl_swiss with MIT License 6 votes vote down vote up
def get_epoch_snapshot(self, epoch):
        """
        Probably will be overridden by each algorithm
        """
        data_to_save = dict(
            epoch=epoch,
            exploration_policy=self.exploration_policy,
        )
        if self.save_environment:
            data_to_save['env'] = self.training_env
        return data_to_save
    
    
    # @abc.abstractmethod
    # def load_snapshot(self, snapshot):
    #     """
    #     Should be implemented on a per algorithm basis
    #     taking into consideration the particular
    #     get_epoch_snapshot implementation for the algorithm
    #     """
    #     pass 
Example #21
Source File: base_algorithm.py    From rl_swiss with MIT License 6 votes vote down vote up
def get_epoch_snapshot(self, epoch):
        """
        Probably will be overridden by each algorithm
        """
        data_to_save = dict(
            epoch=epoch,
            exploration_policy=self.exploration_policy,
        )
        if self.save_environment:
            data_to_save['env'] = self.training_env
        return data_to_save
    
    # @abc.abstractmethod
    # def load_snapshot(self, snapshot):
    #     """
    #     Should be implemented on a per algorithm basis
    #     taking into consideration the particular
    #     get_epoch_snapshot implementation for the algorithm
    #     """
    #     pass 
Example #22
Source File: common.py    From exchangelib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, protocol, chunk_size=None):
        self.chunk_size = chunk_size or CHUNK_SIZE  # The number of items to send in a single request
        if not isinstance(self.chunk_size, int):
            raise ValueError("'chunk_size' %r must be an integer" % chunk_size)
        if self.chunk_size < 1:
            raise ValueError("'chunk_size' must be a positive number")
        self.protocol = protocol

    # The following two methods are the minimum required to be implemented by subclasses, but the name and number of
    # kwargs differs between services. Therefore, we cannot make these methods abstract.

    # @abc.abstractmethod
    # def call(self, **kwargs):
    #     raise NotImplementedError()

    # @abc.abstractmethod
    # def get_payload(self, **kwargs):
    #     raise NotImplementedError() 
Example #23
Source File: ouroboros_api.py    From aggregation with Apache License 2.0 6 votes vote down vote up
def __store_annotations__(self,zooniverse_id,max_users=float("inf"),expert_markings=False):
        """
        override the parent method so that we can apply ROIs
        read through and return all of the relevant annotations associated with the given zooniverse_id
        :param zooniverse_id: id of the subject
        :param max_users: maximum number of classifications to read in
        :param expert_markings: do we want to read in markings from experts - either yes or no, shouldn't mix
        :return:
        """
        if not(zooniverse_id in self.roi_dict):
            self.roi_dict[zooniverse_id] = self.__get_roi__(zooniverse_id)

        self.current_roi = self.roi_dict[zooniverse_id]
        OuroborosAPI.__store_annotations__(self,zooniverse_id,max_users,expert_markings)

        self.current_roi = None

    # @abc.abstractmethod
    # def __classification_to_markings__(self,classification,roi):
    #     """
    #     This is the main function projects will have to override - given a set of annotations, we need to return the list
    #     of all markings in that annotation
    #     """
    #     return [] 
Example #24
Source File: trotterization_base.py    From qiskit-aqua with Apache License 2.0 6 votes vote down vote up
def convert(self, operator: OperatorBase) -> OperatorBase:
        r"""
        Convert a ``SummedOp`` into a ``ComposedOp`` or ``CircuitOp`` representing an
        approximation of e^-i*``op_sum``.

        Args:
            operator: The ``SummedOp`` to evolve.

        Returns:
            The Operator approximating op_sum's evolution.

        Raises:
            TypeError: A non-SummedOps Operator is passed into ``convert``.

        """
        raise NotImplementedError

    # TODO @abstractmethod - trotter_error_bound 
Example #25
Source File: test_abc.py    From Fluid-Designer with 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 #26
Source File: test_abc.py    From Fluid-Designer with 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 #27
Source File: test_final.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def setUpClass(cls):
        FinalABCMeta = compose_types(FinalMeta, ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal 
Example #28
Source File: base_node.py    From tfx with Apache License 2.0 5 votes vote down vote up
def _abstract_property() -> Any:
  """Returns an abstract property for use in an ABC abstract class."""
  return abc.abstractmethod(lambda: None) 
Example #29
Source File: test_final.py    From zipline-chinese with Apache License 2.0 5 votes vote down vote up
def test_cannot_instantiate_subclass(self):
        """
        Tests that you cannot create an instance of a subclass
        that does not implement the abstractmethod h.
        """
        class AbstractSubClass(self.class_):
            pass

        with self.assertRaises(TypeError):
            AbstractSubClass() 
Example #30
Source File: test_inheritance_invariant.py    From icontract with MIT License 5 votes vote down vote up
def test_with_abstract_method(self) -> None:
        @icontract.invariant(lambda self: self.x > 0)
        class A(icontract.DBC):
            def __init__(self) -> None:
                self.x = 10

            @abc.abstractmethod
            def func(self) -> None:
                pass

            def __repr__(self) -> str:
                return "instance of A"

        class B(A):
            def func(self) -> None:
                self.x = -1

            def __repr__(self) -> str:
                return "instance of B"

        b = B()
        violation_error = None  # type: Optional[icontract.ViolationError]
        try:
            b.func()
        except icontract.ViolationError as err:
            violation_error = err

        self.assertIsNotNone(violation_error)
        self.assertEqual("self.x > 0:\n"
                         "self was instance of B\n"
                         "self.x was -1", tests.error.wo_mandatory_location(str(violation_error)))