How to create abstract properties in python abstract classes How to create abstract properties in python abstract classes python python

How to create abstract properties in python abstract classes


Since Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.

Note: Order matters, you have to use @property before @abstractmethod

Python 3.3+: (python docs):

from abc import ABC, abstractmethodclass C(ABC):    @property    @abstractmethod    def my_abstract_property(self):        ...

Python 2: (python docs)

from abc import ABC, abstractpropertyclass C(ABC):    @abstractproperty    def my_abstract_property(self):        ...


Until Python 3.3, you cannot nest @abstractmethod and @property.

Use @abstractproperty to create abstract properties (docs).

from abc import ABCMeta, abstractmethod, abstractpropertyclass Base(object):    # ...    @abstractproperty    def name(self):        pass

The code now raises the correct exception:

Traceback (most recent call last):  File "foo.py", line 36, in     b1 = Base_1('abc')  TypeError: Can't instantiate abstract class Base_1 with abstract methods name


Based on James answer above

def compatibleabstractproperty(func):    if sys.version_info > (3, 3):                     return property(abstractmethod(func))    else:        return abstractproperty(func)

and use it as a decorator

@compatibleabstractpropertydef env(self):    raise NotImplementedError()