1

How can I pass an argument in a function input within the function definition?

For example:

def correlate1(vara1, vara2=vara1*2):
    print "test"

Returns:

Traceback (most recent call last):
  File "test.py", line 321, in <module>
    def correlate1(vara1, vara2=vara*2):
NameError: name 'vara1' is not defined

Obviously, you could do this:

    def correlate1(vara1, vara2=0):
        if vara2==0:
            var2=vara1*2        
        print "test"

But is there a way to do it in the function definition?

1 Answer 1

7

Just set it once the function is called:

def correlate1(vara1, vara2=None):
    vara2 = 2 * vara1 if vara2 is None else vara2

    print "test"

or even more simple:

def correlate2(var1, var2=None):
    var2 = var2 or var1 * 2
    print "test"

var2's default value expression can not contain var1 because var1 does not exist until the function is called.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 because this answer is using None, instead of 0 as the questioner mentioned, to indicate that the 'default interpretation' of vara2 should be used. This matters since vara2 is expected to be a numeric value, thus when called with vara2=0 this could actually be the intended value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.