Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a python abstract base class inherit from object

The standard document about abc, and other tutorials I read all use examples that defines a abstract base class without inheriting from object.

class Foo(object):
    def __getitem__(self, index):
        ...
    def __len__(self):
        ...
    def get_iterator(self):
        return iter(self)

class MyIterable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

In the past I always let my class inherit object to have new-style class. Should I do the same with ABC?

like image 873
swang Avatar asked Feb 17 '26 01:02

swang


1 Answers

Declaring the metaclass of MyIterable to be ABCMeta ensures that instances of MyIterable (or more appropriately, subclasses of MyIterable since it is an Abstract Base Class) will be the "new" style. If you were to create an instance of a subclass of MyIterable as seen below, it would behave as a new style class.

class SubIterable(MyIterable):
    def __iter__(self):
        # your implementation here
        ...

>>> type(SubIterable())
<type '__main__'.MyIterable>

If MyIterable were indeed an "old" style class, type(SubIterable()) would return <type 'instance'>

like image 143
Billy Avatar answered Feb 18 '26 19:02

Billy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!