Skip to content

Instantly share code, notes, and snippets.

@gunnarx
Last active September 9, 2022 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunnarx/97b6e3469e910133713022a555eaee4c to your computer and use it in GitHub Desktop.
Save gunnarx/97b6e3469e910133713022a555eaee4c to your computer and use it in GitHub Desktop.
Python's default values are class attributes... which makes them behave totally weird!

Python implementation issue.

Default values are class attributes, which are shared among all instances!

Reference: https://peps.python.org/pep-0557/#mutable-default-values

So dataclasses tries to fix this...

class X:
   i : int = 0
   s : str = str()
   l : list = []

No problem.

from dataclasses import dataclass
@dataclass
class Y:
   i: int = 0
   s: str = str()
   l: list = []

Output: Initializing with an empty list fails for dataclass:

Traceback (most recent call last):
  File "/tmp/tt", line 8, in <module>
    class Y:
[...]
    raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'list'> for field l is not allowed: use default_factory

For normal classes you get no error, but unexpected behavior:

class X:
   l : list = []

instance1 = X()
instance2 = X()
instance1.l.append("Added to instance 1 only.")

print(f'''
      instance1.l: {instance1.l}
      instance2.l: {instance2.l}
      ''')

Output

      instance1.l: ['Added to instance 1 only.']
      instance2.l: ['Added to instance 1 only.']

😦

@gunnarx
Copy link
Author

gunnarx commented Sep 9, 2022

For more details PEP-0557

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment