Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating a list of functions using globals()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading