Search code examples
pythonfunctionexceptiondefault

Python function - if input variable doesn't exist then use default value


def funcname(var1, var2 = "1234"):

    output = int(var2)

    return output

Is there a way to catch error in case where var2 does not exist i.e. function defines a default value (above) and is called:

result = funcname(var1, var2 = cs) 

but cs does not exist so in case where cs variable does not exist I would like var2 to inherit the default value rather that error as cs not defined.


Solution

  • In your situation you can use try/except

    try: 
        result = function(var1, cs) 
    except NameError: 
        result = function(var1)
    

    But I would rather create variable cs at start with default value

    cs = "1234"
    

    and there is no problem with not existing variable.

    Eventually I would use None

    cs = None
    

    and function would use None to recognize if it should use default value

    #def funcname(var1, var2=None):
    def funcname(var1, var2="1234"):
        if var2 is None:
            var2 = "1234"
        return int(var2)
    

    In some tutorials/books I saw also var2=object when None is correct value which shouldn't be replaced or it should be replaced with different value then default value.

    I neved had to use object for this so I'm not sure if I use it correctly in this example.

    cs = None
    
    def func(var1, var2=object):
        if var2 == object:
            var2 = "1234"
        elif var2 is None:
            var2 = "0"
        return int(var2)
    
    print(func(1))       # 1234
    print(func(1, 2))    # 2
    print(func(1, None)) # 0
    print(func(1, cs))   # 0
    

    But I thing that the best would be create variable cs at start with some value.