Explain Codes LogoExplain Codes Logo

How to import the class within the same directory or sub directory?

python
import-patterns
relative-imports
python-3
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Quickly import classes in Python using dot notation. For a class MyClass in mymodule.py alongside your main.py:

# Yeah, Python is more direct than a bad Tinder date. from mymodule import MyClass

For MyClass in a subdirectory subdir:

# Python believes in long-term relationships with subdirectories. from subdir.mymodule import MyClass

Remember: include an __init__.py file in each directory to make Python treat them as packages. Adjust the path based on your file's location. Use these snippets for a clean and quick import in your code.

Understanding how Python imports work

Python's importing logic

Python follows a certain path search logic when importing. It first checks the directory of the input script or the current directory. Then, it looks in the directories specified in the PYTHONPATH environment variable. If the class isn't found there, Python checks the default path of the installation.

The importance of init.py

Python 3.3 and beyond technically don't require __init__.py in directories. However, including this file is still a good practice. It ensures compatibility and is often necessary for many tools and frameworks. It makes Python treat a directory as a package.

Relative and absolute imports

Relative imports are especially useful within a single project. They are short, neat, and clearly indicate that the imported resource is part of the project.

Advanced import patterns

You might come across scenarios where you need more complex imports. The importlib module allows you to import a source file directly, useful for plugins and extensions that might not follow a standard package structure.

Importing from upper directories

To reach classes in directories above the current location, you can use double-dot notation. It's like asking your parent for permission:

# Mom, can I use your credit card? from ..parent_folder import some_class

Solving circular import issues

Circular imports — when two modules depend on each other — can create headaches. Problem-solving strategies could include importing inside functions or conditional statements, or using type hinting.

Troubleshooting

Problems with imports are often due to missing __init__.py files or incorrect relative import statements. This can lead to a ModuleNotFoundError or ImportError. Double-check your directory structure and ensure your modules are in the right place with the appropriate initialization files.