user5747140
user5747140

Reputation: 197

Passing argument to function assigned to a variable

I realize this is a basic question, but I can't figure out how to answer it. Consider the following code example:

def a_function(someval=None):
    if a_function:
        print(a_function)
    else:
        print("None")

foo = a_function

print(foo(1))

None

I understand I can assign a function (or anything, really) to a variable because functions are first class objections, and that I can call the function via foo().

Question: How do I pass an argument to the function if it is assigned to a variable?

In the example above, it's apparent that the (1) is not being passed to a_function().

Thank you for your help with this.

Upvotes: 1

Views: 69

Answers (3)

Engineero
Engineero

Reputation: 12948

I think your function definition as given in the question is going to always return None.

def a_function(someval=None):
    if someval:
        print(someval)
    else:
        print("None")

And now foo(1) should print 1.

Upvotes: 1

mementum
mementum

Reputation: 3203

Your code simply needs some rework:

def a_function(someval=None):
    print(someval)

foo = a_function

foo(1)

And then the result:

1

Before that you were checking if a_function which is always True because the function is an object and that evaluates to True

And you were additionally printing the return value of a_function which is None because the function has no return statement.

Upvotes: 2

alecxe
alecxe

Reputation: 474191

I think you are asking about functools.partial:

from functools import partial

def a_function(someval=None):
    if someval:
        print(someval)
    else:
        print("None")

foo = partial(a_function, 1)
foo()  # prints 1

foo here is a partial function which "freezes" the a_function function with a specific argument.

Upvotes: 2

Related Questions