python-attrs / attrs

Python Classes Without Boilerplate
https://www.attrs.org/
MIT License
5.31k stars 374 forks source link

complain on mutable default #1242

Closed majidaldo closed 9 months ago

majidaldo commented 9 months ago

Users would expect Out[128] to be 0. Python (built in) dataclasses complains but attrs does not.

@define
class TT:
    tt: float = 0.

@define
class T:
    tt: TT = TT() # need field(factory=lambda: TT())
    t: int = 0

In [124]: t = m.T()
In [125]: t.tt.tt
Out[125]: 0.0
In [126]: t.tt.tt = 3.
In [127]: t = m.T()
In [128]: t.tt.tt
Out[128]: 3.0
hynek commented 9 months ago

Looks like you figured it out on your own! In Python almost everything is mutable and there's plenty of good reasons to set a default to something mutable as long as you're aware of that property. We don't patronize our users.