Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: getting a reference to a function from inside itself

Tags:

If I define a function:

def f(x):     return x+3 

I can later store objects as attributes of the function, like so:

f.thing="hello!" 

I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?

like image 823
Ram Rachum Avatar asked May 12 '09 12:05

Ram Rachum


People also ask

Can you call a function inside of itself Python?

In Python, it's also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively.

How do you call a function inside the same function in Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

How do you call a function within itself?

Recursion is a programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways. When a function calls itself, that's called a recursion step.

Can a function reference itself?

A function can refer to and call itself.


2 Answers

The same way, just use its name.

>>> def g(x): ...   g.r = 4 ... >>> g <function g at 0x0100AD68> >>> g(3) >>> g.r 4 
like image 123
SurDin Avatar answered Sep 22 '22 02:09

SurDin


If you are trying to do memoization, you can use a dictionary as a default parameter:

def f(x, memo={}):   if x not in memo:     memo[x] = x + 3   return memo[x] 
like image 32
Jeff Ober Avatar answered Sep 24 '22 02:09

Jeff Ober