New submission from Aaron Ecay <aarone...@gmail.com>:

I have discovered that InitVar's are passed in a surprising way to the 
__post_init__ method of python dataclasses.  The following program illustrates 
the problem:

=====

from dataclasses import InitVar, dataclass

@dataclass
class Foo:
    bar: InitVar[str]
    quux: InitVar[str]

    def __post_init__(self, quux: str, bar: str) -> None:
        print(f"bar is {bar}; quux is {quux}")

Foo(bar="a", quux="b")

=====

The output (on python 3.7.3 and 3.8.0a3) is (incorrectly):

bar is b; quux is a

This behavior seems like a bug to me, do you agree?

I have not looked into the reason why it behaves this way, but I suspect that 
the InitVar args are passed positionally, rather than as key words, to 
__post_init__.  This requires the order of arguments in the definition of 
__post_init__ to be identical to the order in which they are specified in the 
class.  I would expect the arguments to be passed as keywords instead, which 
would remove the ordering dependency.  If there is agreement that the current 
behavior is undesirable, I can look into creating a patch to change it.

----------
components: Library (Lib)
messages: 356125
nosy: Aaron Ecay
priority: normal
severity: normal
status: open
title: Surprising and possibly incorrect passing of InitVar to __post_init__ 
method of data classes
versions: Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue38719>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to