Type annotation pitfall

Chris Angelico rosuav at gmail.com
Fri Sep 24 09:47:53 EDT 2021


On Fri, Sep 24, 2021 at 11:43 PM Peter Saalbrink
<petersaalbrink at gmail.com> wrote:
>
> I don't think this has anything to do with typing or providing type hints.
> The type hint is the `: set` part, not the `= set()` part.
> You can declare the type without assigning to the variable.
> Indeed, as you already said, `x` is a class property here, and is shared
> amongst instances of the class.
> It might be a good idea to move the attribute assignment to the `__init__`
> method.
>
> In the following way, you can safely provide the type hint:
>
> ```python
> class Foo:
>     x: set
>
>     def __init__(self, s):
>         self.x = set()
>         if s:
>             self.x.add(s)
> ```
>

To be clear, this isn't a case of "never use mutables as class
attributes"; often you *want* a single mutable object to be shared
among instances of a class (so they can all find each other, perhaps).
If you want each instance to have its own set, you construct a new set
every object initialization; if you want them to all use the same set,
you construct a single set and attach it to the class. Neither is
wrong, they just have different meanings.

ChrisA


More information about the Python-list mailing list