Import a module from a relative path
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Importing a module from a relative path in Python can sometimes be challenging, especially for developers new to the environment or working in larger projects with complex folder structures. Understanding how to navigate this is crucial for clean and effective code organization.
Understanding Module Import
Before diving into relative imports, it's essential to understand how Python's import system works. When you import a module, Python searches for it in the directories listed in sys.path
. This search path includes:
- The directory containing the input script (or the current directory).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default directory.
What is a Relative Import?
A relative import specifies an import location in relation to the current module's path. This is particularly useful in packages where modules need to interact frequently. Relative imports rely on dot notation:
- A single
.refers to the current directory containing the module. - Two dots
..refer to the parent directory. - Additional dots (e.g.,
...) navigate up additional directory levels.
Relative imports are only available when you're dealing with package structures and not standalone scripts.
Syntax and Examples
Consider a directory structure for a Python project as follows:
- Namespaces: Helps avoid ambiguity and collision with other modules having the same name.
- Refactoring: Easier to change the structure of packages because imports can stay relative and independent of the top-level structure.
- Readability: Newcomers may find understanding the location of modules less intuitive.
- Flexibility: You cannot use relative imports in standalone scripts, only within package modules.
Related reading
- Import error No module name urllib2
- import input_data MNIST tensorflow not working
- Import Keras on Jupyter Notebook
- Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3
- Import multiple CSV files into pandas and concatenate into one DataFrame
- ImportError cannot import name 'abs
- ImportError cannot import name 'BatchNormalization' from 'keras.layers.normalization
- ImportError cannot import name 'Celery' from 'celery
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.