1
source_code = '''
def fn():
    print('source code executed')
    return 100
exec_val = fn()
'''


class Executor:

    @classmethod
    def run(cls, code):
        exec_val = 0
        exec(code)
        return exec_val


if __name__ == '__main__':
    print(Executor.run(source_code))

>>> source code executed
>>> 0

The result of code above is 0 which is not what I expected 100.
I've tried add global exec_val statement both in source_code and Executor.run, but still not work.

Python 3.6.8

Chweng Mega
  • 1,598
  • 1
  • 13
  • 22
  • I'm not sure how the class-method affects it, but `exec` always returns `None`. You need to pass it `globals()` and/or `locals()` to give the executed code access to the variable `exec_val`. – bnaecker Jun 12 '19 at 04:31
  • Modifications to the `locals()` dict will not necessarily be reflected in the actual local variables. – juanpa.arrivillaga Jun 12 '19 at 04:32

0 Answers0