Import a file from a subdirectory?
Need a quick fix? You can always use the sys.path.append function to add your subdirectory to the system path. Here's an example:
This could serve as a band-aid solution but let's explore the more Pythonic ways to import from a subdirectory.
Setting up Python packages
It's a good practice to group related python files under a subdirectory. To import from such a structure, treat the subdirectory as part of a package.
Package initialization with __init__.py
- Start by creating a subdirectory in your main project directory. Example: lib.
- In lib, add an empty__init__.pyfile. It's like turninglibinto a Hogwarts, visible only to Python wizards.
- Now, you can import a module(named, say, BoxTime) fromlibby:
Want to import a specific function or class from BoxTime? No problem:
Level up with alias
Avoid "name clashes" using a Potions class style alias when importing:
Unlock the hidden scrolls
For other wizards within the castle, relative imports are like a secret handshake:
Handling sys.path like a pro
Modifying sys.path directly is more like using "avada kedavra". It's not advisable. Use pathlib to add reliability:
Be the Python sorcerer that works across muggles' systems.
Practical tips and tricks
Even the best wizards get stuck sometimes. Here are some solutions to keep your magic going.
Avoid re-inventing the spells
Be careful not to name your modules same as standard Python modules. You don't want to create confusion in the magic world.
The lost scroll
Facing a ModuleNotFoundError? Don't panic, validate the following:
- You have correctly placed the spell __init__.py.
- Your path is true.
- You respected case sensitivity.
Accessing library items
To call spells or artifacts in __init__.py directly:
A caution: the spell must be written in the room's __init__.py.
Exploring the castle
Get spells from neighboring rooms like this:
Beware! These won't work if you're running the spells as standalone scrolls. Relative imports are castle-only.
Test your magic
Don't just cast spells. You need to test if they're working as expected.
- Run your spell using Wand(Command Line) or Cauldron(IDE).
- Craft your own potion tests to check if the right spells are invoked.
Was this article helpful?
