creating a list of functions using globals()
Question:
I am trying to define 3 functions.
one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
for item in l:
def _f(): return '::'+item
globals()[item] = _f
del _f
print(one(), two(), three())
However, the three functions are the same, they are equal to the last one. Am I using globals() in the wrong way?
Answers:
Since item
is just a name in the body of _f
, you should define _f
in a scope where item
will have the value you want when you call the function.
You should also not try to inject values into the global namespace like this; just use an ordinary dict
.
def make_function(x):
def _():
return '::' + x
return _
d = {item: make_function(item) for item in ['one', 'two', 'three']}
for f in d.values():
print(f())
I am trying to define 3 functions.
one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
for item in l:
def _f(): return '::'+item
globals()[item] = _f
del _f
print(one(), two(), three())
However, the three functions are the same, they are equal to the last one. Am I using globals() in the wrong way?
Since item
is just a name in the body of _f
, you should define _f
in a scope where item
will have the value you want when you call the function.
You should also not try to inject values into the global namespace like this; just use an ordinary dict
.
def make_function(x):
def _():
return '::' + x
return _
d = {item: make_function(item) for item in ['one', 'two', 'three']}
for f in d.values():
print(f())