Python Question

Is it possible to use an argument's value in a default argument value assignment in Python?

I am trying to use the left-side argument's value in the below function inside of the default argument value to the right.


def function(var, vartwo = var*2):
return vartwo


print(function(7)) #should print 14
print(function(7,6)) #should print 6


However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?

Answer

How about this?

def function(var, vartwo = None):
    if vartwo is None:
        vartwo = var*2;
    return vartwo;

print( function(7));
print(function(7,6));

The hack is to set the default value to None, then set it internally. If not none, then return whatever entered by user.