kjo
kjo

Reputation: 35321

How can a Python function determine if (and how) a kwarg default was explicitly passed?

Suppose a function spam has signature spam(ham=None). The following three calls will all cause the local variable ham in spam's namespace to have value None:

spam()
spam(None)
spam(ham=None)

How can spam find out which of these three alternatives was actually used?

Upvotes: 3

Views: 105

Answers (1)

BrenBarn
BrenBarn

Reputation: 251428

It can't. This question describes a way to use a decorator to wrap the function and set the passed arguments as attributes on it. But there is no way to find out from within spam without help from outside. You have to intercept the call with a function that accepts **kwargs and use that to store the information.

However, you should be cautious of doing this. The different ways of passing in arguments are supposed to work the same. If you do something that makes them work differently, you will confuse many people who try to use your function.

Upvotes: 7

Related Questions