ericvsmith / dataclasses

Apache License 2.0
587 stars 53 forks source link

With a default_factory and init=False, fields are initialized in the wrong order #33

Closed ericvsmith closed 7 years ago

ericvsmith commented 7 years ago

The PEP doesn't say that fields are initialized in order, but I'd like to do so, anyway.

If a field has a default_factory, and has init=False, it is initialized out of order. For this code:

@dataclass
class C:
    x: int
    y: list = field(default_factory=list, init=False)
    z: int

The generated code looks like:

def __init__(__dataclass_self__,x:_type_x,z:_type_z)->_return_type:
 __dataclass_self__.x=x
 __dataclass_self__.z=z
 __dataclass_self__.y = _dflt_y()

I'll rework field initialization to make sure this is handled correctly. I think there are also likely other corner cases.

ilevkivskyi commented 7 years ago

The PEP doesn't say that fields are initialized in order, but I'd like to do so, anyway.

+1 from me, this adds predictability.

gvanrossum commented 7 years ago

Agreed, it's a Python principle that things should be done in the order one would expect. (E.g. a+b is not allowed to evaluate b before a.)

Also, does the self really have to have such an ugly name? (I'd say only if there's a field named self.)

ericvsmith commented 7 years ago

I already have a note to myself to change the naming of "self": I'll pick a new name only if there's a conflict. And it's always possible that the class will have an attribute collision on my "private" name, although I can't get too excited about working around that.