Best practice annotating dataclasses to solve the __init__ problem #1365
Unanswered
randolf-scholz
asked this question in
Q&A
Replies: 1 comment 3 replies
-
Won't something like this work for you? @dataclass
class Foo:
path: Path | str # | whatever
@property
def real_path(self) -> Path:
return Path(self.path).absolute() ? |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What is the best way to avoid this common problem when combining dataclasses with type hints?
We have an attribute that should be of some type, for instance
pathlib.Path
. However, for the init function, it would be desirable to allowstr
as well, and cast it toPath
in__post_init__
. Type hintingPath | str
is problematic if internal methods of the class rely onPath
-methods.Are there any better resolutions than plastering
type: ignore
comments or ditching dataclasses altogether?Beta Was this translation helpful? Give feedback.
All reactions