Chapter 8: Python packages

Running modules in packages

You might have noticed the way I imported other modules in the package in battle/game/manager.py.

I used the full package name e.g. import battle.character.hero, even if the code is in the battle directory. This is the clearest and most unambiguous way recommended by PEP-8.

Another acceptable way to import other modules in the same package is via explicit relative layouts. For example, in battle/character/hero.py, you can import Enemy with from .enemy import Enemy. This is useful if your package name is too long.

Having package level imports also means that you cannot just cd to battle/game/ and run python manager.py from there. Python will not be able to find the module you need to import.

You sometimes do need to test your code for a specific module. For example I have some test code in battle/character/hero.py. The proper way to run a module as a script is to run Python with the -m option (for module) and the full name of the module. For example, run python -m battle.character.hero from the root directory (where main.py is). You should be able to see my test code running.

user@MACHINE:~$ python -m battle.character.hero
Testing hero
Gandalf: Good conquers all!