Question "Is there a way to pass optional parameters to a function?" describes how default keyword parameters are used.
I have two functions, one of which calls the other, and I want to be able to detect if the outer function was called with an optional parameter:
def foo(x1, opt=None):
bar(opt)
def bar(opt=5):
print opt
if __name__ == '__main__':
foo(1) # Should print 5, actually prints None
foo(2, opt=3) # Does print 3
This prints:
None
3
Foo() could be written with special logic to detect whether the optional parameter is passed, but is there a pythonic way to pass an optional parameter with its optionality preserved without using extra logic?
def foo2(x1, opt=None):
if opt is None:
bar()
else:
bar(opt)
The default has to be defined at the inner function because it could be called directly. I could also define the same default for inner and outer functions, but that's a bit ugly (violates DRY) when the default is more complex than an integer.