This repository was archived by the owner on Apr 14, 2022. It is now read-only.
This repository was archived by the owner on Apr 14, 2022. It is now read-only.
Supporting ATTR constructors, just like DATACLASS constructors. #1766
Open
Description
Attrs is a super common library which Python's built-in "dataclass" was based on:
http://www.attrs.org/en/stable/examples.html
Currently, dataclass autocompletion works. The constructor arguments are detected via the dataclass definition.
No such luck for attr classes, despite them being almost the exact same thing.
from dataclasses import dataclass
import attr
@dataclass
class Foo:
zap: int
@attr.s
class Bar:
zap: int
Foo( # <- autocompletes
Bar( # <- no autocompletion
Any chance of attr support? Dataclass is inadequate for a lot of projects, since it's a "lite" version of attrs, so the attrs library has a very big userbase.
Five things would be needed:
- Parsing type from either
zap: int
orzap = attr.ib(type=int)
, since attrs supports both definitions (the latter is the old-school style). Attrs throwsValueError: Type annotation and type argument cannot both be present
if someone tries to mix both styles (iezap: int = attr.ib(type=int)
), even when the user manually disables modern-style via@attr.s(auto_attribs=False)
, so that won't be a concern. Parsing will therefore be very simple: Use the python 3.x type annotationzap: int
if available, else look forzap = attr.ib(type=int)
. It will be either of those but never both... - Parsing keyword-only flag, which is set as
zap: int = attr.ib(kw_only=True)
, which means that the argument can only be provided as a named argument. - Parsing non-init flag, which is set as
zap: int = attr.ib(init=False)
, which means the property isn't included in the constructor parameters. - Parsing the fact that underscore-properties lack an underscore in the constructor, meaning that
_zap: int = attr.ib()
would be__init__(self, zap)
(not__init__(self, _zap)
). This transformation from private (underscore) to public (no underscore) is only done for the constructor argument list. The actual internal properties still have the underscore as provided. - Supporting parent inheritance of attributes from parent classes. In case of inheritance, the rule is very simple when generating the final
__init__
signature: All regular args first, then a, *,
and then all keyword-args. The topmost parent class arguments/kwargs are always listed before the subclass arguments/kwargs, in order of inheritance. So if the topmost class has arg "a" and kwarg "b", and the subclass has arg "c", the final signature would be__init__(a, c, *, b)
.