How to Use Relative Imports in Python?
Relative imports in Python are used to import modules relative to the current module's location in the package hierarchy. They are specified using dot notation to indicate the relative position of the module to be imported. Here's how you can use relative imports:
Suppose you have the following package structure:
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
submodule1.py
Now, if you're in module1.py
and you want to import module2.py
, you can use a relative import:
# module1.py
# Relative import of module2.py
from . import module2
Similarly, if you're in submodule1.py
and you want to import module1.py
, you can use a relative import:
# submodule1.py
# Relative import of module1.py
from .. import module1
In relative imports:
- A single dot
.
refers to the current package. - Two dots
..
refer to the parent package. - You can use multiple dots to traverse up the package hierarchy as needed.
It's important to note that relative imports only work within packages. If you're trying to run a module directly as a script, relative imports will not work. In that case, you should use absolute imports or execute the module as part of a package.
-
How can I import a Python module dynamically given the full path?
Importing programmatically To programmatically import a module, use importlib.import_module(). import importlib itertools = importlib.import_module('itertools') Checking if a module can be imported...
Questions -
Importing files from different folder in Python?
In Python, you can use the import statement to import modules or files from different folders. If the file you want to import is in a different folder than the script you are running, you will need...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github