Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a function to a variable without running it?

Tags:

python

Whenever I assign a variable to a function, it runs the function. As a result, if I were to have a print statement in the function, it would print the text even though all I want to do is assign but not run the function. I don't believe this is the case in many other programming languages such as C++, so is there a core concept that I'm missing here?

def function(x):
    print("Text From Function")
    return 3*x

y = function(2)

I expect there to be no output but the actual output is: Text From Function

like image 434
Loop Avatar asked Dec 31 '22 18:12

Loop


2 Answers

If you have function a and want to assign it to variable y you simply do:

def a():
  print("hello")
y = a
y()

In this case running y() will print "hello". If you use parenthesis after a function it will call it and return whatever the function returns, not the function itself.

like image 164
Anto Avatar answered Feb 24 '23 16:02

Anto


Going from the comments by @ParitoshSingh, @LiranFunaro, and @TrevinAvery, you either want to use a lambda or functools.partial to assign a function with prepopulated arguments to a new name.

import functools

def function(x):
    print("Text From Function")
    return 3*x

y1 = lambda: function(2)
y2 = functools.partial(function, 2)

These are then invoked with y1() and y2().

like image 28
brentertainer Avatar answered Feb 24 '23 17:02

brentertainer