Python abc.ABC Examples

The following are 25 code examples for showing how to use abc.ABC(). 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: dataclasses-json   Author: lidatong   File: api.py    License: MIT License 6 votes vote down vote up
def _process_class(cls, letter_case, undefined):
    if letter_case is not None or undefined is not None:
        cls.dataclass_json_config = config(letter_case=letter_case,
                                           undefined=undefined)[
            'dataclasses_json']

    cls.to_json = DataClassJsonMixin.to_json
    # unwrap and rewrap classmethod to tag it to cls rather than the literal
    # DataClassJsonMixin ABC
    cls.from_json = classmethod(DataClassJsonMixin.from_json.__func__)
    cls.to_dict = DataClassJsonMixin.to_dict
    cls.from_dict = classmethod(DataClassJsonMixin.from_dict.__func__)
    cls.schema = classmethod(DataClassJsonMixin.schema.__func__)

    cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage="init")
    # register cls as a virtual subclass of DataClassJsonMixin
    DataClassJsonMixin.register(cls)
    return cls 
Example 2
Project: differential-privacy-library   Author: IBM   File: test_DPMachine.py    License: MIT License 5 votes vote down vote up
def test_class(self):
        self.assertTrue(issubclass(DPMachine, abc.ABC)) 
Example 3
Project: pex   Author: pantsbuild   File: contextlib2.py    License: Apache License 2.0 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 4
Project: pipenv   Author: pypa   File: contextlib2.py    License: MIT License 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 5
Project: pipenv   Author: pypa   File: contextlib2.py    License: MIT License 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 6
Project: Fluid-Designer   Author: Microvellum   File: test_abc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D') 
Example 7
Project: ironpython3   Author: IronLanguages   File: test_abc.py    License: Apache License 2.0 5 votes vote down vote up
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D') 
Example 8
Project: ctapipe   Author: cta-observatory   File: test_component.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_non_abstract_children():
    """ check that we can find all constructable children """
    from ctapipe.core import non_abstract_children

    class AbstractBase(ABC):
        @abstractmethod
        def method(self):
            pass

    class Child1(AbstractBase):
        def method(self):
            print("method of Child1")

    class Child2(AbstractBase):
        def method(self):
            print("method of Child2")

    class GrandChild(Child2):
        def method(self):
            print("method of GrandChild")

    class AbstractChild(AbstractBase):
        pass

    kids = non_abstract_children(AbstractBase)
    assert Child1 in kids
    assert Child2 in kids
    assert GrandChild in kids
    assert AbstractChild not in kids 
Example 9
Project: permon   Author: bminixhofer   File: __init__.py    License: MIT License 5 votes vote down vote up
def __new__(cls, *args, **kwargs):
        new_class = super().__new__(cls, *args, **kwargs)
        # register the class as stat if it does not immediately inherit ABC
        if ABC not in new_class.__bases__:
            new_class._init_tags()
            cls.stat_classes.append(new_class)
        return new_class 
Example 10
Project: rules_pip   Author: ali5h   File: contextlib2.py    License: MIT License 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 11
Project: cjworkbench   Author: CJWorkbench   File: param_spec.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _RegisterType(type_name):
    """
    Add immutable 'type' field for JSON serialization and connect globals.

    For instance, `class ParamSpecFoo(_RegisterType('foo'), ParamSpec):` means:

    * `_lookup['foo'] == ParamSpecFoo`
    * `ParamSpec.Foo == ParamSpecFoo`
    * ParamSpecFoo(...).type == 'foo'
    """

    @dataclass(frozen=True)
    class ParamSpecType(ABC):
        type: str = field(default=type_name, init=False)

        # override for ABC
        def __init_subclass__(cls, **kwargs):
            name = cls.__name__
            assert name.startswith("ParamSpec")
            subname = name[len("ParamSpec") :]

            super().__init_subclass__(**kwargs)
            _lookup[type_name] = cls
            setattr(ParamSpec, subname, cls)

    return ParamSpecType 
Example 12
Project: pyntcloud   Author: daavoo   File: base.py    License: MIT License 5 votes vote down vote up
def extract_info(cls, pyntcloud):
        """ABC API"""
        info = {
            "points": pyntcloud.xyz
        }
        return info 
Example 13
Project: NeMo   Author: NVIDIA   File: lr_policies.py    License: Apache License 2.0 5 votes vote down vote up
def get_all_lr_classes():
    """ Get all LR classes defined within this module
    """
    lr_classes = {}
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name != 'ABC':
            lr_classes[name] = obj
    return lr_classes 
Example 14
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_abc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D') 
Example 15
Project: choochoo   Author: andrewcooke   File: tree.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _pick_next(self, pair, nodes):
        # avoid ABC error
        raise NotImplementedError() 
Example 16
Project: choochoo   Author: andrewcooke   File: tree.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _pick_seeds(self, nodes):
        # avoid ABC error
        raise NotImplementedError()

    # _exact_area_sum() is on CartesianMixin because it is not abstracted from the coordinate system. 
Example 17
Project: pyparsing   Author: pyparsing   File: core.py    License: MIT License 5 votes vote down vote up
def setName(self, name):
        """
        Define name for this expression, makes debugging and exception messages clearer.
        Example::
            Word(nums).parseString("ABC")  # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)
            Word(nums).setName("integer").parseString("ABC")  # -> Exception: Expected integer (at char 0), (line:1, col:1)
        """
        self.customName = name
        self.errmsg = "Expected " + self.name
        if __diag__.enable_debug_on_named_expressions:
            self.setDebug()
        return self 
Example 18
Project: CogAlg   Author: boris-kz   File: contextlib2.py    License: MIT License 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 19
Project: Tautulli   Author: Tautulli   File: contextlib2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __subclasshook__(cls, C):
        """Check whether subclass is considered a subclass of this ABC."""
        if cls is AbstractContextManager:
            return _check_methods(C, "__enter__", "__exit__")
        return NotImplemented 
Example 20
Project: pydantic   Author: samuelcolvin   File: test_abc.py    License: MIT License 5 votes vote down vote up
def test_model_subclassing_abstract_base_classes():
    class Model(BaseModel, abc.ABC):
        some_field: str 
Example 21
Project: pydantic   Author: samuelcolvin   File: test_abc.py    License: MIT License 5 votes vote down vote up
def test_model_subclassing_abstract_base_classes_without_implementation_raises_exception():
    class Model(BaseModel, abc.ABC):
        some_field: str

        @abc.abstractmethod
        def my_abstract_method(self):
            pass

        @classmethod
        @abc.abstractmethod
        def my_abstract_classmethod(cls):
            pass

        @staticmethod
        @abc.abstractmethod
        def my_abstract_staticmethod():
            pass

        @property
        @abc.abstractmethod
        def my_abstract_property(self):
            pass

        @my_abstract_property.setter
        @abc.abstractmethod
        def my_abstract_property(self, val):
            pass

    with pytest.raises(TypeError) as excinfo:
        Model(some_field='some_value')
    assert str(excinfo.value) == (
        "Can't instantiate abstract class Model with abstract methods "
        "my_abstract_classmethod, my_abstract_method, my_abstract_property, my_abstract_staticmethod"  # noqa: Q000
    ) 
Example 22
Project: selene   Author: yashaka   File: entity.py    License: MIT License 5 votes vote down vote up
def should(self, condition: Condition[E]) -> E:
        pass


# todo: try as Matchable(ABC) and check if autocomplete will still work 
Example 23
Project: autogluon   Author: awslabs   File: base_classes.py    License: Apache License 2.0 5 votes vote down vote up
def next_candidates(self) -> List[Candidate]:
        # Not using ABC otherwise it will be difficult to create a subclass that also is a
        # NamedTuple(as both define their own metaclass)
        raise NotImplemented("Abstract method") 
Example 24
Project: siuba   Author: machow   File: datetime.py    License: MIT License 5 votes vote down vote up
def _make_abc(name, subclasses):
    cls = type(name, (ABC,), {})
    for child in subclasses: cls.register(child)
    return cls 
Example 25
Project: pyradigm   Author: raamana   File: base.py    License: MIT License 4 votes vote down vote up
def __init__(self,
                 target_type=float,
                 dtype=float,
                 allow_nan_inf=False,
                 encode_nonnumeric=False,
                 ):
        """Init for the ABC to define the type and properties of the Dataset

        Parameters
        -----------
        target_type : type, callable
            Data type of the target for the child class.
            Must be callable that takes in a datatype and converts to its own type.

        dtype : np.dtype
            Data type of the features to be stored

        allow_nan_inf : bool or str
            Flag to indicate whether raise an error if NaN or Infinity values are
            found. If False, adding samplets with NaN or Inf features raises an error
            If True, neither NaN nor Inf raises an error. You can pass 'NaN' or
            'Inf' to specify which value to allow depending on your needs.
        """

        if not callable(target_type):
            raise TypeError('target type must be callable, to allow for conversion!')
        else:
            self._target_type = target_type

        if np.issubdtype(dtype, np.generic):
            self._dtype = dtype
        else:
            raise TypeError('data type for features {} not recognized!'
                            'It must be a subdtype of np.generic'
                            ''.format(dtype))

        if not isinstance(allow_nan_inf, (bool, str)):
            raise TypeError('allow_nan_inf flag can only be bool or str')
        else:
            self._allow_nan_inf = allow_nan_inf

        if not isinstance(encode_nonnumeric, bool):
            raise TypeError('encode_nonnumeric flag can only be bool')
        else:
            self._encode_nonnumeric = encode_nonnumeric

        # samplet-wise attributes
        self._attr = dict()
        self._attr_dtype = dict()
        # dataset-wise attributes, common to all samplets
        self._dataset_attr = dict()