Checking default arguments

Steven Bethard steven.bethard at gmail.com
Fri Feb 2 14:23:36 EST 2007


Igor V. Rafienko wrote:
> I was wondering whether it was possible to find out which parameter
> value is being used: the default argument or the user-supplied one.
> That is:  
> 
> def foo(x, y="bar"):
>     # how to figure out whether the value of y is 
>     # the default argument, or user-supplied?
> 
> foo(1, "bar") => user-supplied
> foo(1)        => default

Why are you trying to make this distinction? That is, why should passing 
in "bar" be any different from getting the default value "bar"

You could do something like::

     >>> def foo(x='b a r'):
     ...     if x is foo.func_defaults[0]:
     ...         print 'default'
     ...     else:
     ...         print 'supplied'
     ...
     >>> foo('b a r')
     supplied
     >>> foo()
     default

But that won't really work if your default value gets interned by 
Python, like small integers or identifier-like string literals::

     >>> def foo(x='bar'):
     ...     if x is foo.func_defaults[0]:
     ...         print 'default'
     ...     else:
     ...         print 'supplied'
     ...
     >>> bar = ''.join(chr(i) for i in [98, 97, 114])
     >>> foo(bar)
     supplied
     >>> foo('bar')
     default


STeVe



More information about the Python-list mailing list