Skip to content
Advertisement

Python3 exec, why returns None?

When the code below this text, and returns the result None why?

with open('exx.py', 'rb') as file:
ff = compile(file.read(), 'exx.py', 'exec')
snip_run = exec(ff, locals())
if 'result' in locals():
    print(snip_run, result)
else:
    print(snip_run)

Result:

777777
None

Module code exx.py:

print('777777')

Advertisement

Answer

The problem of course is not only that print returns None, it is that exec returns None, always.

>>> exec('42') is None
True

If you’d need the return value, you’d use eval:

>>> eval('42')
42

after which you’d notice that print still returns None

Advertisement