2

My code structure:

/foo
    __init__.py
    bar.py

init.py

import bar
eval("import bar")

It raises SyntaxError when execute the second line.

>>> import foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "foo/__init__.py", line 2, in <module>
    eval('import bar')
  File "<string>", line 1
    import bar
         ^
SyntaxError: invalid syntax

I am confused because I would expect behaviors of these codes should be the same.

gzc
  • 8,180
  • 8
  • 42
  • 62

1 Answers1

3

You can use exec instead if you intend to import the module:

exec("import bar")
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139