2

I am trying to store a function as a variable and pass parameters to the function through the variable. So for example, consider this:

def the_funct(*args):
    the_sum = 0
    for arg in args:
        the_sum += arg
    return the_sum

If I set the function like this: the_var = the_funct()

And then try to call it like this:

    print('the var: ' + str(the_var(5)))
    print('***********')

It throws a type error like this: TypeError: 'int' object is not callable

If I do this:

print('the var: ' + str(the_var))
    print('***********')

It evaluates.

So I think I'm missing something fundamental about passing parameters into functions that are stored as variables...any ideas for what it might be? Other threads I've read suggest the above should work.

3
  • the_var is not a function, so why are you calling it? Commented Dec 1, 2019 at 14:34
  • the_var = the_funct() You asked python to "run"/call the function, and then assigned only the return of it. Note the brackets after the_funct() . If you want to assign the function, don't call the function, leave the brackets out. Commented Dec 1, 2019 at 14:35
  • @Austin: I want to be able to pass the function around like a lambda but without the limitation presented by lambdas. There may be better ways of doing this than what I'm attempting, so any ideas are welcome Commented Dec 1, 2019 at 14:36

2 Answers 2

4
If I set the function like this: the_var = the_funct()

This way you asked for result of the_funct, which is 0 without parameters.

If you want to alias your function, use the_var = the_funct

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

1 Comment

Just what I needed; thanks! I'll accept it as the answer after SO allows me to
3

the_var = the_funct() executes the definition of the_funct and assigns the return value back to the var, which is an integer. Hence when you try to call the_var(5), the integer is being used as a function, hence the error TypeError: 'int' object is not callable

the_var = the_funct()
print(the_var) #Outputs 0

You want to instead do the_var = the_funct which assigns the name of function to the_var

the_var = the_funct
print(the_var) #Outputs <function the_funct at ......>

Your output then will be

the var: 5
***********

Comments

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.