Why an InitVar pseudo field in dataclasses cannot have a default_factory?
Jacobo de Vera
devel at jacobodevera.com
Wed Jul 17 05:06:30 EDT 2019
Hi all,
I was surprised by an error when trying to set a default_factory for an
InitVar pseudo-field in a dataclass. Inspecting the code in dataclasses.py
led me to this:
# Special restrictions for ClassVar and InitVar.
if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
if f.default_factory is not MISSING:
raise TypeError(f'field {f.name} cannot have a '
'default factory')
# Should I check for other field settings? default_factory
# seems the most serious to check for. Maybe add others. For
# example, how about init=False (or really,
# init=<not-the-default-init-value>)? It makes no sense for
# ClassVar and InitVar to specify init=<anything>.
So this case is very explicitly prevented but I could not see why. Does
anybody know what problem this is trying to prevent or what is the
rationale behind this restriction?
I asked in stackoverflow[1] and I was suggested to ask here.
[1] https://stackoverflow.com/questions/57056029
Thanks,
Jacobo de Vera
@jovianjake
More information about the Python-list
mailing list