84

Let's say I have a function

def x():
    print(20)

Now I want to assign the function to a variable called y, so that if I use the y it calls the function x again. if i simply do the assignment y = x(), it returns None.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
stensootla
  • 13,945
  • 9
  • 45
  • 68
  • 3
    I've edited your question to cut it down to the [relevant information only.](http://meta.stackexchange.com/a/128552/102937). Your enthusiasm is great, but in future please focus on explaining your actual question. – Li-aung Yip Apr 27 '12 at 16:22
  • 1
    I also edited as what you want to do here is *assign a function to a variable*, not *assign a variable to a function*. – Gareth Latty Apr 27 '12 at 16:29
  • I think `lambda ` should work, pls. check my answer below. – Pengju Zhao Apr 11 '18 at 04:40

7 Answers7

133

You simply don't call the function.

>>> def x():
>>>     print(20)
>>> y = x
>>> y()
20

The brackets tell Python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • 10
    Functions as first-class objects, *oh yeah*. – Li-aung Yip Apr 27 '12 at 16:15
  • 1
    Thank you very much. Up until now, i actually somehow thought that i was pretty decent in Python :D – stensootla Apr 27 '12 at 16:15
  • 7
    @geekkid: It's worth noting that **any** object can be made "callable", like a function. All you have to do is define the `__call__()` method of the object. – Li-aung Yip Apr 27 '12 at 16:23
  • Yes, ofcourse. I couldn't accept it right before you posted the answer, because the website wouldn't let me accept an answer so soon. Thank you all for your responses. – stensootla Apr 27 '12 at 19:50
  • Can you do this with class instances? – jimh Dec 11 '15 at 22:08
  • 2
    @semjaavria Sure, methods work in the same way - try it. – Gareth Latty Dec 11 '15 at 22:13
  • @Latty thanks man, that's great to know. this whole thread was really helpful. – jimh Dec 12 '15 at 00:38
  • @GarethLatty I have a related question: When i type y = x() into the console why does it output 20? I was merely attempting to assign the function to a variable, but this command actually executes the function, why is this? – seeker Oct 09 '16 at 20:06
  • @seeker I'm not sure what I can say that I didn't already in the answer. `()` is the signal you are calling the function. The function itself is `x` - `x()` means 'take x and call it with no arguments'. Do `y = x` and then later `y()` to call it. – Gareth Latty Oct 09 '16 at 22:46
  • @GarethLatty I just want know why it's called even when you write: y = x() . In my console 20 shows up when I write y = x(). Why is this when I haven't explicitly called the function? – seeker Oct 09 '16 at 22:49
  • 2
    @seeker `x()` is explicitly calling the function. `x` is an expression that returns the function `x`. `x()` is an expression that returns the result of calling the function `x`. `y = x()` is assigning the result of calling the function to `y`, `y = x` is assigning the function to `y`. The fact it appears in an assignment doesn't make `x()` mean a different thing. – Gareth Latty Oct 09 '16 at 22:51
  • This is what I'm saying! When I type y = x() in Windows power shell 20 is displayed after I hit enter. Usually when you assign a value to a variable nothing appears on the next line, but in this case 20 does. Why is this? – seeker Oct 09 '16 at 22:53
  • @seeker Because your function is being called. In order to get the result of `x()`, `x` must be run. In this case, it runs, printing `20` and returning `None`. Then that result (`None`) is assigned to `y`. Functions in Python (as with most languages) can have side effects. In order to call the function to get it's return value (or `None` if it has no explicit return value), the function is executed, and side effects happen. – Gareth Latty Oct 09 '16 at 22:55
  • Oh thank you, this is all I wanted to know. It was driving me mad not knowing why that was appearing! Thanks – seeker Oct 09 '16 at 22:56
  • @seeker to better undestand your issue, you should check also [Levon's](http://stackoverflow.com/a/10354207/1262357) answer. – Gruber Dec 15 '16 at 06:37
  • What if the function is `x(z)`, and `z` is defined later? – alex Oct 09 '19 at 15:52
  • @alex As explained in the answer, `x(z)` is an expression that calls the function `x` with the argument `z`, not a function. – Gareth Latty Oct 10 '19 at 15:54
  • thanks, but what if i want to have like ```some_var = "x"``` and then ```y = some_var```. i want not to use if/else statements and want to call ```x``` function. – Tanmay Bairagi Feb 28 '23 at 10:07
17

When you assign a function to a variable you don't use the () but simply the name of the function.

In your case given def x(): ..., and variable silly_var you would do something like this:

silly_var = x

and then you can call the function either with

x()

or

silly_var()
Levon
  • 138,105
  • 33
  • 200
  • 191
12

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

cobie
  • 7,023
  • 11
  • 38
  • 60
10

The syntax

def x():
    print(20)

is basically the same as x = lambda: print(20) (there are some differences under the hood, but for most pratical purposes, the results the same).

The syntax

def y(t):
   return t**2

is basically the same as y= lambda t: t**2. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x to be the function lambda: print(20). So x now refers to that function. x() is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:

def power_function(power):
      return  lambda x : x**power
power_function(3)(2)

This returns 8. power_function is a function that returns a function as output. When it's called on 3, it returns a function that cubes the input, so when that function is called on the input 2, it returns 8. You could do cube = power_function(3), and now cube(2) would return 8.

Acccumulation
  • 3,491
  • 1
  • 8
  • 12
5

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

Pengju Zhao
  • 1,439
  • 3
  • 14
  • 17
  • This did not work for the print function. I was trying to dependency inject my choice of 'logging' to a custom function. – AnneTheAgile Sep 18 '19 at 15:09
0

I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:

import sys
fun = eval(sys.argv[1])
fun()

In the present case, fun = x.

Apostolos
  • 3,115
  • 25
  • 28
0
def x():
   print(20)
   return 10

y = x
y()
print(y)

gives the output

20
<function x at 0x7fc548cd3040>

so it does not actually assign the value returned by x() to the variable y.

muratozyurt
  • 101
  • 8