Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting kwarg override in Python

Tags:

python

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.

like image 576
Colton Myers Avatar asked Jan 18 '26 15:01

Colton Myers


1 Answers

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
like image 149
NPE Avatar answered Jan 20 '26 05:01

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!