from abc import abstractmethod, ABCMeta
class AbstractBase(object):
__metaclass__ = ABCMeta
#abstractmethod
def must_implement_this_method(self):
raise NotImplementedError()
class ConcreteClass(AbstractBase):
def extra_function(self):
print('hello')
# def must_implement_this_method(self):
# print("Concrete implementation")
d = ConcreteClass() # no error
d.extra_function()
I'm on Python 3.4. I want to define an abstract base class that defines somes functions that need to be implemented by it's subclassses. But Python doesn't raise a NotImplementedError when the subclass does not implement the function...
The syntax for the declaration of metaclasses has changed in Python 3. Instead of the __metaclass__ field, Python 3 uses a keyword argument in the base-class list:
import abc
class AbstractBase(metaclass=abc.ABCMeta):
#abc.abstractmethod
def must_implement_this_method(self):
raise NotImplementedError()
Calling d = ConcreteClass() will raise an exception now, because a metaclass derived from ABCMeta can not be instantiated unless all of its abstract methods and properties are overridden (For more information see #abc.abstractmethod):
TypeError: Can't instantiate abstract class ConcreteClass with abstract methods
must_implement_this_method
Hope this helps :)
Related
Why Python allows the abstract methods to be implemented in the abstract base class when they are meant to be overridden by the derived class anyway?
from abc import ABC, abstractmethod
class AbstractClassExample(ABC):
#abstractmethod
def do_something(self):
print("Some implementation!")
class AnotherSubclass(AbstractClassExample):
def do_something(self):
super().do_something()
print("The enrichment from AnotherSubclass")
x = AnotherSubclass()
x.do_something()
I would like to create an abstract method in parent class which would be overridden in subclasses. This method would print all methods in the given subclass which start with 'on_'.
from abc import ABC, abstractmethod
class abstract_class(ABC):
#abstractmethod
def get_all_on_methods(self):
pass
class sub(abstract_class):
an_object = sub()
def get_all_on_methods(self):
for attribute in dir(self):
if attribute.startswith("on_"):
print(attribute)
def nothin(self):
print("nothin")
def on_fallback(self):
raise NotImplementedError()
def on_no(self):
raise NotImplementedError()
sub.get_all_on_methods()
I have two problems. First, I have:
Unresolved reference 'sub'
Second, I don't know whether my approach as actually all that good.
I have an Interface class which defines the requirements to an active "in-use" class:
class Portfolio(ABC):
#abstractmethod
def update_portfolio(self):
raise NotImplementedError
#abstractmethod
def update_from_fill(self):
raise NotImplementedError
#abstractmethod
def check_signal(self, signal_event):
raise NotImplementedError
The methods update_portfolio and update_from_fill are both methods which will be the same in 99% of the required cases. Only the check_signal method will vary. Therefore, to avoid having to write the same code again and again, I have defined a base class with default methods for update_portfolio and update_from_fill:
class BaseBacktestPortfolio(Portfolio):
def __init__(self, ...):
...
def update_portfolio(self, ...):
...
def update_from_fill(self, ...):
...
Then, finally, I have a class inheriting from the BacktestPortfolio class which specifies the correct implementation of the check_signal method:
class USBacktestPortfolio(BaseBacktestPortfolio):
def check_signal(self, ...):
...
Now, the problem is that my editor complains about the BacktestPortfolio classing not having all the required abstract methods. I could ignore this, of course, but the perfect scenario would be if I could make sure that it is not possible to instantiate an object form the BacktestPortfolio class.
Is this possible? And/or is there a more correct way to implement a structure like this?
I could ignore this, of course, but the perfect scenario would be if I could make sure that it is not possible to instantiate an object from the BacktestPortfolio class.
That is the case in your example already:
>>> BaseBacktestPortfolio.mro()
[__main__.BaseBacktestPortfolio, __main__.Portfolio, abc.ABC, object]
>>> BaseBacktestPortfolio()
TypeError: Can't instantiate abstract class BaseBacktestPortfolio with abstract methods check_signal
Since ABC and ABCMeta are just regular types, their features are inherited. This includes their guards against instantiating incomplete classes. Your BaseBacktestPortfolio already is an abstract class.
The warning from your IDE/linter/... exists specifically to warn you that instantiating BaseBacktestPortfolio is not possible.
You can make the BaseBacktestPortfolio also as Abstract class.
from abc import ABC, abstractmethod
class Portfolio(ABC):
#abstractmethod
def update_portfolio(self):
pass
#abstractmethod
def update_from_fill(self):
pass
#abstractmethod
def check_signal(self, signal_event):
pass
class BaseBacktestPortfolio(Portfolio, ABC):
def update_portfolio(self):
print("updated portfolio")
def update_from_fill(self):
print("update from fill")
#abstractmethod
def check_signal(self):
pass
class USBacktestPortfolio(BaseBacktestPortfolio):
def check_signal(self):
print("checked signal")
Also notice that you don't need raise NotImplementedError inside abstract method. You can just pass. Its more Pythonic :)
I have one base class with abstractmethod and subclass which implements this method. How to determine in runtime if in object (without checking type of object or calling method) that method is abstract or not?
class Base:
#abc.abstractmethod
def someAbstractMethod(self):
raise NotImplementedError("Not implemented yet.")
class Subclass(Base):
def someAbstractMethod(self):
some_operations
objects = [Base(),Subclass(),Base(),Subclass(),Subclass(),...]
for object in objects:
#here I want check if method is still abstract or not
Python prevents the creation of instances for classes with abstract methods. So just the fact that you have an instance means you have no abstract methods.
You do, however, have to use the ABCMeta metaclass to properly trigger this behaviour:
class Base(metaclass=abc.ABCMeta):
#abc.abstractmethod
def someAbstractMethod(self):
raise NotImplementedError("Not implemented yet.")
You can also inherit from abc.ABC to get the same metaclass via a base class.
If you wanted to see what abstract methods a class might have listed, use the __abstractmethods__ attribute; it is a set of all names that are still abstract:
>>> import abc
>>> class Base(metaclass=abc.ABCMeta):
... #abc.abstractmethod
... def someAbstractMethod(self):
... raise NotImplementedError("Not implemented yet.")
...
>>> class Subclass(Base):
... def someAbstractMethod(self):
... some_operations
...
>>> Base.__abstractmethods__
frozenset({'someAbstractMethod'})
>>> Subclass.__abstractmethods__
frozenset()
All that the #abc.abstractmethod decorator does is set a __isabstractmethod__ attribute on the function object; it is the metaclass that then uses those attributes.
So if you are dig in too deep or are using a third-party library that has forgotten to use the ABCMeta metaclass, you can test for those attributes:
>>> class Base: # note, no metaclass!
... #abc.abstractmethod
... def someAbstractMethod(self):
... raise NotImplementedError("Not implemented yet.")
...
>>> getattr(Base().someAbstractMethod, '__isabstractmethod__', False)
True
If you need to 'repair' such broken abstract base classes, you'd need subclass and mix in ABCMeta, and add a __abstractmethods__ frozenset to the class you are inheriting from:
BaseClass.__abstractmethods__ = frozenset(
name for name, attr in vars(BaseClass).items()
if getattr(attr, '__isabstractmethod__', False))
class DerivedClass(BaseClass, metaclass=abc.ABCMeta):
# ...
Now DerivedClass is a proper ABC-derived class where any abstract methods are properly tracked and acted on.
You're not using abc correctly here (well not as it's intended to be used at least). Your Base class should use abc.ABCMeta as metaclass, which would prevent instanciation of child classes not implementing abstractmethods. Else just using the abc.abstractmethod decorator is mostly useless.
Python 2.7:
class Base(object):
__metaclass__ = abc.ABCMeta
#abc.abstractmethod
def someAbstractMethod(self):
# no need to raise an exception here
pass
Python 3.x
class Base(metaclass=abc.ABCMeta):
#abc.abstractmethod
def someAbstractMethod(self):
# no need to raise an exception here
pass
In python, can I define an interface (abstract class) by inheritance from another abstract class?
If I try:
import abc
ABC = abc.ABCMeta('ABC', (object,), {})
class interface(ABC):
#abc.abstractmethod
def method(self, message):
return
class InterfaceExtended(ABC, interface):
#abc.abstractmethod
def NewMethod(self, message):
return
I get an error on the "InterfaceExtended" class :
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases ABC, Interface
Don't inherit from ABC in your second class. The interface it derives from already inherits ABC