Typed alternatives to building a dict of kwargs #1875
Unanswered
stephenfin
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I see the following pattern fairly regularly:
where
foo
,bar
, andbaz
are all valid optional kwargs formyfunction
. For example: [1], [2], [3].In virtually all cases, the code is written this way because (a) we want to avoid duplicating/overriding the default defined on the method or (b) the method cares about the difference between "unset" and "null" values which Python doesn't currently have a native way to handle (pending PEP-661 or a similar PEP).
The closest thing to a solution that I've found is to declare a
TypedDict
but that gets real tedious, real fast and still results in some level of duplication:I could de-duplicate somewhat using
typing.Unpack
for the actual method or function signature but that leaves code difficult to read and IMO isn't the intended purpose of that utility.What I think I want is a way to statically retrieve the type hints for a function/method and use those like so:
but such a thing doesn't appear to exist, nor do I think it would be possible given e.g. the fact that decorators can "manipulate" arguments.
Would anyone be able to share/point to some best practices around this that allow us to avoid duplicating parameter defaults and/or passing
None
where that value has semantic meaning?PS: Apologies if this has been asked before. I'm almost certain it will have been (likely many times) but if so my search-fu has failed me 😞
Beta Was this translation helpful? Give feedback.
All reactions