Skip to content

Attribute without type hint in slotted class can't be changed  #1173

@rklasen

Description

@rklasen

Hi, so I've just stumbled over something I assume is a misunderstanding on my part, but I want to ask to be sure.

I have a slotted class without type hints:

@define
class Scenario:
    momentum = 0.0
    trackDirectory: Path = Path()

From the default value of 0.0 I assumed attrs would infer the type of momentum, but when I try to change the value, I get an error:

>>> scen = Scenario(trackDirectory=".")
>>> scen.momentum = 15.09
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Scenario' object attribute 'momentum' is read-only
>>> type(scen.momentum)
<class 'float'>

So the type is a float as expected, but I can not change the value of momentum.


But when I add a type hint:

@define
class Scenario:
    momentum: float = 0.0
    trackDirectory: Path = Path()

All works as expected:

>>> scen = Scenario(trackDirectory=".")
>>> scen.momentum = 15.09
>>> type(scen.momentum)
<class 'float'>

So, is this expected/desired behavior and I'm just misunderstanding something? Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions