Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python variable value for default argument

In Python, what value can a variable take, so that when a function is invoked with the variable as an argument, the function uses its default value for the parameter instead?

Consider the following code:

def foo(a=100):
    print(a)

b = None #blank value
foo(b)

Desired output:
100

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Actual output:
None

I hypothesized that None would work, but clearly it doesn’t. What value can I choose for b, so that foo(b) is equivalent to foo()? Or is this simply not possible? I’m in a situation where the value for b can either be defined, or I would like to use the default value of the parameter.

>Solution :

(This answer assumes that you cannot modify foo, and that you cannot use reflection or introspection to determine what the default argument value is.)


It’s the absence of an argument, not any particular value used as an argument, that triggers the use of the default value. The only way you can produce nothing out of something is to unpack an empty mapping

foo(**{})

or an empty sequence

foo(*())

Both * and ** are part of the function-call syntax, though, not part of the argument value, so with a variable, it still looks like

b = {}
foo(**b)

b = ()
foo(*b)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading