23

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?

Ram Rachum
  • 84,019
  • 84
  • 236
  • 374

3 Answers3

21

The same way, just use its name.

>>> def g(x):
...   g.r = 4
...
>>> g
<function g at 0x0100AD68>
>>> g(3)
>>> g.r
4
SurDin
  • 3,281
  • 4
  • 26
  • 28
  • I was confused by the output formatting, but recognized the code and answer is solid (+1). This is what the "usual" Python REPL shows, and should be more recognizable for more people. What interpreter did you use? –  Oct 12 '10 at 12:57
3

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]
Jeff Ober
  • 4,967
  • 20
  • 15
3

Or use a closure:

def gen_f():
    memo = dict()
    def f(x):
        try:
            return memo[x]
        except KeyError:
            memo[x] = x + 3
    return f
f = gen_f()
f(123)

Somewhat nicer IMHO