How to import the class within the same directory or sub directory?
Quickly import classes in Python using dot notation. For a class MyClass
in mymodule.py
alongside your main.py
:
For MyClass
in a subdirectory subdir
:
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:
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.
Was this article helpful?