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

Create dynamic function in python?

I got NameError for calling test_gobject, but the funny thing is I never called this function name. I called test_gobjectpy()
Can you explain it to me why Python decide to call the wrong function name (see error output)

Maybe it has some problems because I have a string with the same name as function?!

file name test_dyn_fun.py

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

second_path = ['test_gobject.py', 'st1.py', 'test_show_desktop.py', 'download_img.py', 'test_dump.py']
print("second_path", second_path)
print()
for i in second_path:
    #func = create_dyn_func(i)
    tmp = i.replace(".", "")  #rm dot for function name
    print("tmp =", tmp)
    exec(f"def {tmp}(): print({i})")
print()
print(dir(test_gobjectpy))
print()
print(locals())
test_gobjectpy()

Error output:

Traceback (most recent call last):
  File "/home/manta/Coding/test_dyn_fun.py", line 13, in <module>
    test_gobjectpy()
  File "<string>", line 1, in test_gobjectpy
NameError: name 'test_gobject' is not defined

>Solution :

In your loop you create functions, the first one created is effectively created like this:

i = 'test_gobject.py' 
tmp = 'test_gobjectpy'
exec(f"def {tmp}(): print({i})")

So, it’s as if you ran:

exec("def test_gobjectpy(): print(test_gobject.py)")

For Python to print test_gobject.py, it tries to access an object called test_gobject and its attribute .py.

That’s what is causing the error. The fact that test_gobject.py looks like a filename to you doesn’t matter, it’s just names of variables to Python, the way you wrote it.

What would you expect to happen if you called this function?

def test_gobjectpy():
    print(test_gobject.py)

More in general, as a beginning programmer, it’s generally best to stay away from stuff like exec() and eval(). It’s very common for new Python programmers to think they need this, or that it somehow solves a problem they have, but it’s generally the worst solution to the problem and rarely actually a good solution at all. (not never, just rarely)

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