[Python-Dev] Issues with PEP 526 Variable Notation at the class level

Eric V. Smith eric at trueblade.com
Thu Dec 7 15:47:38 EST 2017


On 12/7/17 3:27 PM, Raymond Hettinger wrote:
...

> I'm looking for guidance or workarounds for two issues that have arisen.
>
> First, the use of default values seems to completely preclude the use of __slots__.  For example, this raises a ValueError:
>
>     class A:
>         __slots__ = ['x', 'y']
>         x: int = 10
>         y: int = 20

Hmm, I wasn't aware of that. I'm not sure I understand why that's an 
error. Maybe it could be fixed?

Otherwise, I have a decorator that takes a dataclass and returns a new 
class with slots set:

 >>> from dataclasses import dataclass
 >>> from dataclass_tools import add_slots
 >>> @add_slots
... @dataclass
... class C:
...   x: int = 0
...   y: int = 0
...
 >>> c = C()
 >>> c
C(x=0, y=0)
 >>> c.z = 3
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'z'

This doesn't help the general case (your class A), but it does at least 
solve it for dataclasses. Whether it should be actually included, and 
what the interface would look like, can be (and I'm sure will be!) argued.

The reason I didn't include it (as @dataclass(slots=True)) is because it 
has to return a new class, and the rest of the dataclass features just 
modifies the given class in place. I wanted to maintain that conceptual 
simplicity. But this might be a reason to abandon that. For what it's 
worth, attrs does have an @attr.s(slots=True) that returns a new class 
with __slots__ set.

> The second issue is that the different annotations give different signatures than would produced for manually written classes.  It is unclear what the best practice is for where to put the annotations and their associated docstrings.

I don't have any suggestions here.

Eric.


More information about the Python-Dev mailing list