1

I'd like do something like this:

f = lambda x: None

x = [f]

def f(n):
    return n

print x[0](2)

Expected result is 2, but it's actually None.

I know it's possible to solve with classes, but can it be done without them?

Mkoch
  • 1,994
  • 2
  • 13
  • 21
  • 1
    Nope, not without doing `x[0] = f` again. Does [this previous answer of mine](http://stackoverflow.com/questions/12080552/python-list-doesnt-reflect-variable-change-new-to-python/12080644#12080644) shed some light why this doesn't work in any way? – Martijn Pieters Feb 07 '13 at 21:40
  • Well, @MartijnPieters previous answer is great (as always), just don't understand what a serious use-case is, given your example. – Jon Clements Feb 07 '13 at 21:49

4 Answers4

0

Here you are creating an anonymous function and adding it to a list. Now there are two references pointing to the lambda. Although you define another function with same name f, this does not effect the reference in the list as it points to the lambda.

What are you trying to achieve here?

Ifthikhan
  • 1,484
  • 10
  • 14
0

You are storing a reference to the function in the list x not its name.

you could do something like

f = lambda x: None
x = ['f']
def f(n):
    return n

print globals()[x[0]](2)

but this is kinda "bad". Maybe you could explain why you are trying to do that and we can find you a better way.

cmd
  • 5,754
  • 16
  • 30
0

You can set f as a global variable:

global f
f = lambda x: x+1

x = f

x(1)

OUT: 2

f = lambda x: x+2

x = f

x(1)

OUT: 3

Rick
  • 563
  • 3
  • 6
  • 24
0

Hmm, that's easy (:. Function is a object as anything else. What about doing

x = [f]

or

x[0] = f

after you redefined f?

jary
  • 1,161
  • 6
  • 9