Search code examples
pythonfunctionconfigparser

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:

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.