I am looking for a way to detect whether a keyword arg was passed in explicitly, without using **kwargs.
Here is an example:
def foo(first, second=None):
pass
If, in this function, I find that second contains None, is there a way to know whether that None was from the default, or was passed in explicitly? Basically, I have an optional argument that could conceivably be any value or type. So I either need some sort of "unique" default such that the user would never intentionally pass in that default, or I need a way to detect whether the argument was actually passed in explicitly.
I expect I could discover it by inspecting the stack, but I feel like that's overkill.
I also know I could do it this way:
def foo(first, **kwargs):
if 'second' in kwargs:
# Overridden!
pass
But I would prefer not to accept **kwargs, as it makes my function signature less useful and can hide errors.
You can always create a unique object and use it as the default:
_default = object()
def foo(first, second=_default):
if second is not _default:
# Overridden!
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With