I’m relatively new to a lot of Python features, and found myself updating an codebase to use dataclasses’ InitVar.
When looking into how to pass the args, I came across this old issue. TLDR: InitVars are passed to post_init by position, not keyword.
For backwards compatibility reasons, it’s probably too late to change the default behavior to pass by keyword. However, I excitedly implemented a simple way to tell dataclass to pass InitVars via keyword, using def __post_init__(self, *, initvar1, initvar2…
EDIT] (added example for better explanation)
# new ability, notice the * in def
# called as __post_init__(self, x=x, y=y)
@dataclass
class Foo:
x: InitVar[int]
y: InitVar[int]
def __post_init__(self, *, y, x):
print(f”{x=}, {y=}”)
# backwards compatible
# post_init without *arg collector
# __post_init__(self, x, y)
@dataclass
class Foo:
x: InitVar[int]
y: InitVar[int]
def __post_init__(self, my_x, my_y):
print(my_x, my_y)
[\End Edit]
My question: would anyone actually use it, or is this the case of “leave good enough alone”?
On the plus side, you can safely reorganize your InitVars without worrying about modifying post_init. Another (small plus): throw a “*” in post_init and compare a debug print to make sure your args in the right order?
How important is that for your codebase?