Explain Codes LogoExplain Codes Logo

Import a file from a subdirectory?

python
importing-modules
package-structure
python-best-practices
Alex KataevbyAlex Kataev·Feb 23, 2025
TLDR

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:

import sys # Swap below path to your actual subfolder sys.path.append('/path/to/subdirectory') import your_module # Replace this with your module name

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

  1. Start by creating a subdirectory in your main project directory. Example: lib.
  2. In lib, add an empty __init__.py file. It's like turning lib into a Hogwarts, visible only to Python wizards.
mkdir lib touch lib/__init__.py # Make some magic happen
  1. Now, you can import a module(named, say, BoxTime) from lib by:
import lib.BoxTime # Unleash the BoxTime!

Want to import a specific function or class from BoxTime? No problem:

from lib.BoxTime import your_time_function

Level up with alias

Avoid "name clashes" using a Potions class style alias when importing:

import lib.BoxTime as BoxLib # Call it whatever you want, just don't call it late for dinner

Unlock the hidden scrolls

For other wizards within the castle, relative imports are like a secret handshake:

from .subdirectory import file_to_import

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:

from pathlib import Path sys.path.append(str(Path(__file__).resolve().parent / 'subdirectory'))

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:

from lib import some_spell

A caution: the spell must be written in the room's __init__.py.

Exploring the castle

Get spells from neighboring rooms like this:

from ..neighbor_room import neighbor_spell

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.

  1. Run your spell using Wand(Command Line) or Cauldron(IDE).
  2. Craft your own potion tests to check if the right spells are invoked.