2021-12-01

Dataclass in python does not raise error when the class variable is assigned as a list (but does with typing hints)

I'm just trying to get myself familiar with dataclass in python. One thing I learned from some readings online is that, we can turn the regular class definition with a mutable class variable (which is a bad thing), into dataclass and that would prevent it. For example:

regular class:

class A:
    a = []
    
    def __init__(self):
        self.b = 1

this could have potential issue where different instances share the same class variable a, and modify a unknowingly.

and with dataclass:

@dataclass
class A:
    a: list = []

    def __init__(self):
        self.b = 1

this does not allow me to write this class by raising error:

ValueError: mutable default <class 'list'> for field a is not allowed: use default_factory

however, if I simply get rid of the type annotation:

@dataclass
class A:
    a = []

    def __init__(self):
        self.b = 1

there is no complaint at all and a is still shared across different instances.

Is this expected?

How come the simple type annotation would change the behavior of the class variable?

(I'm using python 3.7.6)



from Recent Questions - Stack Overflow https://ift.tt/3d4wbdO
https://ift.tt/eA8V8J

No comments:

Post a Comment