NI6
NI6

Reputation: 2907

Python - attrs class inheriting from abstract class

I'm curious how attrs can be combined with abstract classes. I Want to define an abstract class, that defines abstract properties which every inheriting class must have.

I want use attrs for this inheriting class, to define its properties. So I tried playing a little bit with both:

import abc
import attr

class Parent(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def x(self):
        pass


@attr.s()
class Child(Parent):
    x = attr.ib()


c = Child(9)
c.x = 7

raises the following error:

AttributeError: can't set attribute

Perhaps there is a way to declare a property to be abstract using attrs?:

@attr.s()
class Parent(object):
    __metaclass__ = abc.ABCMeta
    x = attr.ib(abstract=True)

If one finds a better way to gain the benefits of the two modules I'll be very grateful!

Many thanks in advance!

Upvotes: 6

Views: 5951

Answers (1)

Well, note that x = attr.ib() is not creating a property; it's setting an attribute.

Your example code fails at c = Child(9), because when attrs tries to set the attribute, it fails on account of the attribute being read-only, as defined by the ABC (since it didn't include a setter).

The attributes being set by attrs are what one thinks of as "instance variables". There is no mechanism in Abstract Base Classes (that I'm aware of, even in Python 3) to describe instance variables as part of the abstract interface.

So there's no inherrent conflict here between attrs and ABCs, but attrs attributes are not properties.

Upvotes: 3

Related Questions