Python abc.ABC Examples

The following are 25 code examples of abc.ABC(). 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: api.py    From dataclasses-json with 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
Source File: test_abc.py    From Project-New-Reign---Nemesis-Main with 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 #3
Source File: datetime.py    From siuba with 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 #4
Source File: base_classes.py    From autogluon with 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 #5
Source File: entity.py    From selene with 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 #6
Source File: test_abc.py    From pydantic with 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 #7
Source File: test_abc.py    From pydantic with MIT License 5 votes vote down vote up
def test_model_subclassing_abstract_base_classes():
    class Model(BaseModel, abc.ABC):
        some_field: str 
Example #8
Source File: contextlib2.py    From Tautulli with 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 #9
Source File: contextlib2.py    From CogAlg with 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 #10
Source File: core.py    From pyparsing with 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 #11
Source File: tree.py    From choochoo with 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 #12
Source File: tree.py    From choochoo with GNU General Public License v2.0 5 votes vote down vote up
def _pick_next(self, pair, nodes):
        # avoid ABC error
        raise NotImplementedError() 
Example #13
Source File: test_DPMachine.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_class(self):
        self.assertTrue(issubclass(DPMachine, abc.ABC)) 
Example #14
Source File: lr_policies.py    From NeMo with 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 #15
Source File: base.py    From pyntcloud with MIT License 5 votes vote down vote up
def extract_info(cls, pyntcloud):
        """ABC API"""
        info = {
            "points": pyntcloud.xyz
        }
        return info 
Example #16
Source File: param_spec.py    From cjworkbench with 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 #17
Source File: contextlib2.py    From rules_pip with 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 #18
Source File: __init__.py    From permon with 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 #19
Source File: test_component.py    From ctapipe with 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 #20
Source File: test_abc.py    From ironpython3 with 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 #21
Source File: test_abc.py    From Fluid-Designer with 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 #22
Source File: contextlib2.py    From pipenv with 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 #23
Source File: contextlib2.py    From pipenv with 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 #24
Source File: contextlib2.py    From pex with 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 #25
Source File: base.py    From pyradigm with 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()