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
It is not possible with the normal import mechanism unless you make
Gamea package (i.e., by putting an__init__.pyinside theGamedirectory). 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 dofrom ..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.pydirectly 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.