简体   繁体   中英

Import in a module fails because __name__ is __main__

Here is my project structure:

Project
   main.py
   myPackage/
      subfolder1/
         __init__.py
         script11.py
         script12.py
      subfolder2/
         __init__.py
         script2.py
   __init__.py

in main.py I import script2.py the following way :

from myPackage.subfolder2 import script2 as script2

then, I call a function from script2.py in main.py with :

bar = script2.foo()

and in script2 I need to import a function from script1 :

from ..subfolder1.script11 import my_function

and it breaks with the error :

attempted relative import with no known parent package

I have inspected the __name__ variable and indeed it has the value __main__ . How can I manage that properly ?

All you should have to do is change your import in main.py to from myPackage.subfolder2 import script2 . I set up a directory and some files in this way, using that import, and the script runs as expected:

main.py
myPackage/
  subfolder1/
    script11.py
  subfolder2/
    script2.py

script11.py

def bar():
    return 10

script2.py

from ..subfolder1.script11 import bar

def foo():
    x = bar()
    print('foo is', x)

main.py

from myPackage.subfolder2 import script2 as s2

s2.foo()

Running:

>>> py .\main.py
foo is 10

Some notes:

  • I'm assuming Python 3, since Python 2 was deprecated beginning of this year
  • In Python 3, the __init__.py files aren't necessary to make a package, but having them doesn't hurt anything. You can leave them out if you want.
  • The as script2 part in from subfolder2 import script2 as script2 is redundant. It will already be imported as script2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM