Importing another module from another subdirectory of the current directory's parent directory (python)

眉间皱痕 提交于 2019-12-13 04:28:54

问题


I'm attempting to write a game. I therefore have lots of different types of code and want to arrange them in a useful hierarchy.

I've looked at solutions that involve placing __init__.py in each folder but I'm still somewhat confused, though not as much as the python interpreter.

Now suppose resource1.py wants to import a function from physics1.py, or indeed any other .py file in the Game directory, how would I go about doing so?

I've tried from bin.physics.physics1 import function but obviously that doesn't work.

Thanks for your help.

/Game
    launcher.py
    /bin
        game.py
        __init__.py
        /physics
            __init__.py
            physics1.py
            physics2.py
    /resources
        __init__.py
        resource1.py

回答1:


It is not possible with the normal import mechanism unless you make Game a package (i.e., by putting an __init__.py inside the Game directory). The python relative import system only works within packages. It is not a general system for referring to arbitrary modules by their location in the directory structure. If you make Game a package, then you could do from ..bin.physics.physics1 import function.

Edit: Note also that relative imports don't work from a script executed as the main program. If you try to run resource.py directly and it uses relative imports, you'll get a "relative import attempted in non-package" error. It will work if you import resource from another module. This is because the relative import system is based on the "name" of the executing module, and when you run a script directly its name is __main__ instead of whatever it would usually be named. It's possible to get around this using the __package__ keyword if you really need to, but it can be a bit tricky.



来源:https://stackoverflow.com/questions/11335830/importing-another-module-from-another-subdirectory-of-the-current-directorys-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!