On 12/8/2017 1:28 PM, Raymond Hettinger wrote:
On Dec 7, 2017, at 12:47 PM, Eric V. Smith <e...@trueblade.com> wrote:
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?
The way __slots__ works is that the type() metaclass automatically assigns
member-objects to the class variables 'x' and 'y'. Member objects are
descriptors that do the actual lookup.
So, I don't think the language limitation can be "fixed". Essentially, we're
wanting to use the class variables 'x' and 'y' to hold both member objects and a default
value.
Thanks. I figured this out after doing some research. Here's a thread
"__slots__ and default values" from 14+ years ago from some guy named
Hettinger:
https://mail.python.org/pipermail/python-dev/2003-May/035575.html
As to whether we add slots=True to @dataclasses, I'll let Guido decide.
The code already exists as a separate decorator here:
https://github.com/ericvsmith/dataclasses/blob/master/dataclass_tools.py#L3,
if you want to play with it.
Usage:
>>> @add_slots
... @dataclass
... class A:
... x: int = 10
... y: int = 20
...
>>> a = A()
>>> a
A(x=10, y=20)
>>> a.x = 15
>>> a
A(x=15, y=20)
>>> a.z = 30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'z'
Folding it in to @dataclass is easy enough. On the other hand, since it
just uses the dataclasses public API, it's not strictly required to be
in @dataclass.
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.
I'm hoping the typing experts will chime in here. The question is
straight-forward. Where should we look for the signature and docstring for
constructing instances? Should they be attached to the class, to __init__(),
or to __new__() when it used.
It would be nice to have an official position on that before, it gets set in
stone through arbitrary choices made by pycharm, pydoc, mypy,
typing.NamedTuple, and dataclasses.dataclass.
I'm not sure I see why this would relate specifically to typing, since I
don't think they'd inspect docstrings. But yes, it would be good to come
to an agreement.
Eric.
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com