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

execute a function inside another function

I have this configuration file (test_conf.txt):

[function]
exptime1 = |def foo(f):
           |    result=float(f['a'])
           |    return result

and this code that works without problem

c = configparser.ConfigParser()
c.read('test_conf.txt')
e1 = compile(c['function']['exptime1'].replace('|', ''), '', 'exec')
exec(e1)
f = {'a':2, 'b':'3'}
print(foo(f))

nevertheless, when I put this inside another function:

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

def run():
    c = configparser.ConfigParser()
    c.read('test_conf.txt')
    e1 = compile(c['function']['exptime1'].replace('|', ''), '', 'exec')
    f = {'a':2, 'b':'3'}
    exec(e1)
    print(foo(f))

I have this error:

NameError: name foo is not defined

using dir() the function foo is in the NameSpace but somehow it is not recognized

>Solution :

Let me reproduce your problem without any config parser.

common section

e1 = '''def foo(f):
    result = float(f['a'])
    return result
'''

f = {'a': 2, 'b': '3'}

working

exec(e1)
print(foo(f))
#outputs 2.0

not working

def run():
    exec(e1)
    print(foo(f))

run()
NameError: name foo is not defined

I got same output by exec(e1,globals()). ref

disclamation

I’m not sure how it works, but it does work for your current problem.

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