In Python 3.4+, we can do
class Foo(abc.ABC): ...
or we can do
class Foo(metaclass=abc.ABCMeta): ...
Are there any differences between the two that I should be aware of?
ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class.
The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes. 'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator.
abc.ABC
basically just an extra layer over metaclass=abc.ABCMeta
. i.e abc.ABC
implicitly defines the metaclass for us.
(Source: https://hg.python.org/cpython/file/3.4/Lib/abc.py#l234)
class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ pass
The only difference is that in the former case you need a simple inheritance and in the latter you need to specify the metaclass.
From What's new in Python 3.4(emphasis mine):
New class
ABC
hasABCMeta
as its meta class. UsingABC
as a base class has essentially the same effect as specifyingmetaclass=abc.ABCMeta
, but is simpler to type and easier to read.
Related issue: Create abstract base classes by inheritance rather than a direct invocation of __metaclass__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With