Search code examples
pythonargument-passingfunction-declaration

How to declare an optional argument (mode) in the function(non_optional, mode="bla bla") in Python?


How to declare an optional argument in a function, that takes at least 1 real (non-optional) argument in Python?

Here's an example:

def myfunc(data, mode='never_mind'):
    if mode == 'never_mind:
        return 
    elif mode == 'print':
        print "Input data:", data
        # do something with data...
    elif mode == 'sqrt':
        print "%f is a square root of %f (input data)" % (data ** 0.5, data)
    else:
        print "Invalid input mode."

# I want to declare a new function as myfunc() with predeclared mode='sqrt' (for example).
# How can I do it?

new_func = myfunc
new_func.mode = 'sqrt'            # it doesn't work!

# or...

new_func = myfunc(mode='sqrt')    # it doesn't work either!

Solution

  • Checkout functools.partial.

    In [1]: from functools import partial
    
    In [2]: def f(a, b="b"):
       ...:     print(a, b)
       ...:     
    
    In [3]: g = partial(f, b="c")
    
    In [4]: g("a")
    a c