đŸ•·ïž Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 71 (from laksa099)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

â„č Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
6 days ago
đŸ€–
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.2 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://realpython.com/absolute-vs-relative-python-imports/
Last Crawled2026-04-16 14:12:22 (6 days ago)
First Indexed2018-09-19 14:56:36 (7 years ago)
HTTP Status Code200
Content
Meta TitleAbsolute vs Relative Imports in Python – Real Python
Meta DescriptionIf you’ve worked on a Python project that has more than one file, chances are you’ve had to use an import statement before. In this tutorial, you’ll not only cover the pros and cons of absolute and relative imports but also learn about the best practices for writing import statements.
Meta Canonicalnull
Boilerpipe Text
If you’ve worked on a Python project that has more than one file, chances are you’ve had to use an import statement before. Even for Pythonistas with a couple of projects under their belt, imports can be confusing! You’re probably reading this because you’d like to gain a deeper understanding of imports in Python, particularly absolute and relative imports. In this tutorial, you’ll learn the differences between the two, as well as their pros and cons. Let’s dive right in! A Quick Recap on Imports You need to have a good understanding of Python modules and packages to know how imports work. A Python module is a file that has a .py extension, and a Python package is any folder that has modules inside it (or, in Python 2, a folder that contains an __init__.py file). What happens when you have code in one module that needs to access code in another module or package? You import it! How Imports Work But how exactly do imports work? Let’s say you import a module abc like so: The first thing Python will do is look up the name abc in sys.modules . This is a cache of all modules that have been previously imported. If the name isn’t found in the module cache, Python will proceed to search through a list of built-in modules. These are modules that come pre-installed with Python and can be found in the Python Standard Library . If the name still isn’t found in the built-in modules, Python then searches for it in a list of directories defined by sys.path . This list usually includes the current directory, which is searched first. When Python finds the module, it binds it to a name in the local scope. This means that abc is now defined and can be used in the current file without throwing a NameError . If the name is never found, you’ll get a ModuleNotFoundError . You can find out more about imports in the Python documentation here ! Syntax of Import Statements Now that you know how import statements work, let’s explore their syntax. You can import both packages and modules. (Note that importing a package essentially imports the package’s __init__.py file as a module.) You can also import specific objects from a package or module. There are generally two types of import syntax. When you use the first one, you import the resource directly, like this: abc can be a package or a module. When you use the second syntax, you import the resource from another package or module. Here’s an example: xyz can be a module, subpackage, or object, such as a class or function. You can also choose to rename an imported resource, like so: This renames the imported resource abc to other_name within the script. It must now be referenced as other_name , or it will not be recognized. Styling of Import Statements PEP 8 , the official style guide for Python , has a few pointers when it comes to writing import statements. Here’s a summary: Imports should always be written at the top of the file, after any module comments and docstrings . Imports should be divided according to what is being imported. There are generally three groups: standard library imports (Python’s built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application) Each group of imports should be separated by a blank line. It’s also a good idea to order your imports alphabetically within each import group. This makes finding particular imports much easier, especially when there are many imports in a file. Here’s an example of how to style import statements: The import statements above are divided into three distinct groups, separated by a blank space. They are also ordered alphabetically within each group. Absolute Imports You’ve gotten up to speed on how to write import statements and how to style them like a pro. Now it’s time to learn a little more about absolute imports. An absolute import specifies the resource to be imported using its full path from the project’s root folder. Syntax and Practical Examples Let’s say you have the following directory structure: There’s a directory, project , which contains two sub-directories, package1 and package2 . The package1 directory has two files, module1.py and module2.py . The package2 directory has three files: two modules, module3.py and module4.py , and an initialization file, __init__.py . It also contains a directory, subpackage , which in turn contains a file, module5.py . Let’s assume the following: package1/module2.py contains a function, function1 . package2/__init__.py contains a class, class1 . package2/subpackage1/module5.py contains a function, function2 . The following are practical examples of absolute imports: Note that you must give a detailed path for each package or file, from the top-level package folder. This is somewhat similar to its file path, but we use a dot ( . ) instead of a slash ( / ). Pros and Cons of Absolute Imports Absolute imports are preferred because they are quite clear and straightforward. It is easy to tell exactly where the imported resource is, just by looking at the statement. Additionally, absolute imports remain valid even if the current location of the import statement changes. In fact, PEP 8 explicitly recommends absolute imports. Sometimes, however, absolute imports can get quite verbose, depending on the complexity of the directory structure. Imagine having a statement like this: That’s ridiculous, right? Luckily, relative imports are a good alternative in such cases! Relative Imports A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won’t be covering them here. Syntax and Practical Examples The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported. Here are a few examples of relative imports: You can see that there is at least one dot in each import statement above. Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above. Three dots mean that it is in the grandparent directory, and so on. This will probably be familiar to you if you use a Unix-like operating system! Let’s assume you have the same directory structure as before: Recall the file contents: package1/module2.py contains a function, function1 . package2/__init__.py contains a class, class1 . package2/subpackage1/module5.py contains a function, function2 . You can import function1 into the package1/module1.py file this way: You’d use only one dot here because module2.py is in the same directory as the current module, which is module1.py . You can import class1 and function2 into the package2/module3.py file this way: In the first import statement, the single dot means that you are importing class1 from the current package. Remember that importing a package essentially imports the package’s __init__.py file as a module. In the second import statement, you’d use a single dot again because subpackage1 is in the same directory as the current module, which is module3.py . Pros and Cons of Relative Imports One clear advantage of relative imports is that they are quite succinct. Depending on the current location, they can turn the ridiculously long import statement you saw earlier to something as simple as this: Unfortunately, relative imports can be messy, particularly for shared projects where directory structure is likely to change. Relative imports are also not as readable as absolute ones, and it’s not easy to tell the location of the imported resources. Conclusion Good job for making it to the end of this crash course on absolute and relative imports! Now you’re up to speed on how imports work. You’ve learned the best practices for writing import statements, and you know the difference between absolute and relative imports. With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long. Thanks for reading!
Markdown
[![Real Python](https://realpython.com/static/real-python-logo.893c30edea53.svg)](https://realpython.com/) - [Start Here](https://realpython.com/start-here/) - [Learn Python](https://realpython.com/absolute-vs-relative-python-imports/) [Python Tutorials → In-depth articles and video courses](https://realpython.com/search?kind=article&kind=course&order=newest) [Learning Paths → Guided study plans for accelerated learning](https://realpython.com/learning-paths/) [Quizzes & Exercises → Check your learning progress](https://realpython.com/quizzes/) [Browse Topics → Focus on a specific area or skill level](https://realpython.com/tutorials/all/) [Community Chat → Learn with other Pythonistas](https://realpython.com/community/) [Office Hours → Live Q\&A calls with Python experts](https://realpython.com/office-hours/) [Live Courses → Live, instructor-led Python courses](https://realpython.com/live/) [Podcast → Hear what’s new in the world of Python](https://realpython.com/podcasts/rpp/) [Books → Round out your knowledge and learn offline](https://realpython.com/products/books/) [Reference → Concise definitions for common Python terms](https://realpython.com/ref/) [Code Mentor →Beta Personalized code assistance & learning tools](https://realpython.com/mentor/) [Unlock All Content →](https://realpython.com/account/join/) - [More](https://realpython.com/absolute-vs-relative-python-imports/) [Learner Stories](https://realpython.com/learner-stories/) [Python Newsletter](https://realpython.com/newsletter/) [Python Job Board](https://www.pythonjobshq.com/) [Meet the Team](https://realpython.com/team/) [Become a Contributor](https://realpython.com/jobs/) - [Search](https://realpython.com/search "Search") - [Join](https://realpython.com/account/join/) - [Sign‑In](https://realpython.com/account/login/?next=%2Fabsolute-vs-relative-python-imports%2F) [Browse Topics](https://realpython.com/tutorials/all/) [Guided Learning Paths](https://realpython.com/learning-paths/) [Basics](https://realpython.com/search?level=basics) [Intermediate](https://realpython.com/search?level=intermediate) [Advanced](https://realpython.com/search?level=advanced) *** [ai](https://realpython.com/tutorials/ai/) [algorithms](https://realpython.com/tutorials/algorithms/) [api](https://realpython.com/tutorials/api/) [best-practices](https://realpython.com/tutorials/best-practices/) [career](https://realpython.com/tutorials/career/) [community](https://realpython.com/tutorials/community/) [databases](https://realpython.com/tutorials/databases/) [data-science](https://realpython.com/tutorials/data-science/) [data-structures](https://realpython.com/tutorials/data-structures/) [data-viz](https://realpython.com/tutorials/data-viz/) [devops](https://realpython.com/tutorials/devops/) [django](https://realpython.com/tutorials/django/) [docker](https://realpython.com/tutorials/docker/) [editors](https://realpython.com/tutorials/editors/) [flask](https://realpython.com/tutorials/flask/) [front-end](https://realpython.com/tutorials/front-end/) [gamedev](https://realpython.com/tutorials/gamedev/) [gui](https://realpython.com/tutorials/gui/) [machine-learning](https://realpython.com/tutorials/machine-learning/) [news](https://realpython.com/tutorials/news/) [numpy](https://realpython.com/tutorials/numpy/) [projects](https://realpython.com/tutorials/projects/) [python](https://realpython.com/tutorials/python/) [stdlib](https://realpython.com/tutorials/stdlib/) [testing](https://realpython.com/tutorials/testing/) [tools](https://realpython.com/tutorials/tools/) [web-dev](https://realpython.com/tutorials/web-dev/) [web-scraping](https://realpython.com/tutorials/web-scraping/) [Table of Contents](https://realpython.com/absolute-vs-relative-python-imports/#toc) - [A Quick Recap on Imports](https://realpython.com/absolute-vs-relative-python-imports/#a-quick-recap-on-imports) - [How Imports Work](https://realpython.com/absolute-vs-relative-python-imports/#how-imports-work) - [Syntax of Import Statements](https://realpython.com/absolute-vs-relative-python-imports/#syntax-of-import-statements) - [Styling of Import Statements](https://realpython.com/absolute-vs-relative-python-imports/#styling-of-import-statements) - [Absolute Imports](https://realpython.com/absolute-vs-relative-python-imports/#absolute-imports) - [Syntax and Practical Examples](https://realpython.com/absolute-vs-relative-python-imports/#syntax-and-practical-examples) - [Pros and Cons of Absolute Imports](https://realpython.com/absolute-vs-relative-python-imports/#pros-and-cons-of-absolute-imports) - [Relative Imports](https://realpython.com/absolute-vs-relative-python-imports/#relative-imports) - [Syntax and Practical Examples](https://realpython.com/absolute-vs-relative-python-imports/#syntax-and-practical-examples_1) - [Pros and Cons of Relative Imports](https://realpython.com/absolute-vs-relative-python-imports/#pros-and-cons-of-relative-imports) - [Conclusion](https://realpython.com/absolute-vs-relative-python-imports/#conclusion) Mark as Completed Share Recommended Course [![Absolute vs Relative Imports in Python](https://files.realpython.com/media/imports.9d65e7197280.jpg) Absolute vs Relative Imports in Python 16m · 4 lessons](https://realpython.com/courses/absolute-vs-relative-imports-python/) ![Absolute vs Relative Imports in Python](https://files.realpython.com/media/imports.9d65e7197280.jpg) # Absolute vs Relative Imports in Python by [Mbithe Nzomo](https://realpython.com/absolute-vs-relative-python-imports/#author) Reading time estimate 9m [33 Comments](https://realpython.com/absolute-vs-relative-python-imports/#reader-comments) [intermediate](https://realpython.com/tutorials/intermediate/) [best-practices](https://realpython.com/tutorials/best-practices/) [python](https://realpython.com/tutorials/python/) Mark as Completed Share Table of Contents - [A Quick Recap on Imports](https://realpython.com/absolute-vs-relative-python-imports/#a-quick-recap-on-imports) - [How Imports Work](https://realpython.com/absolute-vs-relative-python-imports/#how-imports-work) - [Syntax of Import Statements](https://realpython.com/absolute-vs-relative-python-imports/#syntax-of-import-statements) - [Styling of Import Statements](https://realpython.com/absolute-vs-relative-python-imports/#styling-of-import-statements) - [Absolute Imports](https://realpython.com/absolute-vs-relative-python-imports/#absolute-imports) - [Syntax and Practical Examples](https://realpython.com/absolute-vs-relative-python-imports/#syntax-and-practical-examples) - [Pros and Cons of Absolute Imports](https://realpython.com/absolute-vs-relative-python-imports/#pros-and-cons-of-absolute-imports) - [Relative Imports](https://realpython.com/absolute-vs-relative-python-imports/#relative-imports) - [Syntax and Practical Examples](https://realpython.com/absolute-vs-relative-python-imports/#syntax-and-practical-examples_1) - [Pros and Cons of Relative Imports](https://realpython.com/absolute-vs-relative-python-imports/#pros-and-cons-of-relative-imports) - [Conclusion](https://realpython.com/absolute-vs-relative-python-imports/#conclusion) [Remove ads](https://realpython.com/account/join/) Recommended Course [Absolute vs Relative Imports in Python](https://realpython.com/courses/absolute-vs-relative-imports-python/) (16m) If you’ve worked on a Python project that has more than one file, chances are you’ve had to use an import statement before. Even for Pythonistas with a couple of projects under their belt, imports can be confusing! You’re probably reading this because you’d like to gain a deeper understanding of imports in Python, particularly absolute and relative imports. In this tutorial, you’ll learn the differences between the two, as well as their pros and cons. Let’s dive right in\! **Free Bonus:** [5 Thoughts On Python Mastery](https://realpython.com/bonus/python-mastery-course/), a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level. ## A Quick Recap on Imports You need to have a good understanding of [Python modules and packages](https://realpython.com/python-modules-packages/) to know how imports work. A Python module is a file that has a `.py` extension, and a Python package is any folder that has modules inside it (or, in Python 2, a folder that contains an `__init__.py` file). What happens when you have code in one module that needs to access code in another module or package? You import it\! [Remove ads](https://realpython.com/account/join/) ### How Imports Work But how exactly do imports work? Let’s say you import a module `abc` like so: Python ``` import abc ``` The first thing Python will do is look up the name `abc` in [`sys.modules`](https://docs.python.org/3/library/sys.html#sys.modules). This is a cache of all modules that have been previously imported. If the name isn’t found in the module cache, Python will proceed to search through a list of built-in modules. These are modules that come pre-installed with Python and can be found in the [Python Standard Library](https://docs.python.org/3/library/). If the name still isn’t found in the built-in modules, Python then searches for it in a list of directories defined by [`sys.path`](https://docs.python.org/3/library/sys.html#sys.path). This list usually includes the current directory, which is searched first. When Python finds the module, it binds it to a name in the local scope. This means that `abc` is now defined and can be used in the current file without throwing a `NameError`. If the name is never found, you’ll get a `ModuleNotFoundError`. You can find out more about imports in the Python documentation [here](https://docs.python.org/3/reference/import.html)\! **Note: Security Concerns** Be aware that Python’s import system presents some significant security risks. This is largely due to its flexibility. For example, the module cache is writable, and it is possible to override core Python functionality using the import system. Importing from third-party packages can also expose your application to security threats. Here are a couple of interesting resources to learn more about these security concerns and how to mitigate them: - [10 common security gotchas in Python and how to avoid them](https://hackernoon.com/10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03) by Anthony Shaw (Point 5 talks about Python’s import system.) - [Episode \#168: 10 Python security holes and how to plug them](https://talkpython.fm/episodes/show/168/10-python-security-holes-and-how-to-plug-them) from the TalkPython podcast (The panelists begin talking about imports at around the 27:15 mark.) ### Syntax of Import Statements Now that you know how import statements work, let’s explore their syntax. You can import both packages and modules. (Note that importing a package essentially imports the package’s `__init__.py` file as a module.) You can also import specific objects from a package or module. There are generally two types of import syntax. When you use the first one, you import the resource directly, like this: Python ``` import abc ``` `abc` can be a package or a module. When you use the second syntax, you import the resource from another package or module. Here’s an example: Python ``` from abc import xyz ``` `xyz` can be a module, subpackage, or object, such as a class or function. You can also choose to rename an imported resource, like so: Python ``` import abc as other_name ``` This renames the imported resource `abc` to `other_name` within the script. It must now be referenced as `other_name`, or it will not be recognized. ### Styling of Import Statements [PEP 8](http://pep8.org/#imports), the official [style guide for Python](https://realpython.com/python-code-quality/), has a few pointers when it comes to writing import statements. Here’s a summary: 1. Imports should always be written at the top of the file, after any module comments and [docstrings](https://realpython.com/how-to-write-docstrings-in-python/). 2. Imports should be divided according to what is being imported. There are generally three groups: - standard library imports (Python’s built-in modules) - related third party imports (modules that are installed and do not belong to the current application) - local application imports (modules that belong to the current application) 3. Each group of imports should be separated by a blank line. It’s also a good idea to order your imports alphabetically within each import group. This makes finding particular imports much easier, especially when there are many imports in a file. Here’s an example of how to style import statements: Python ``` ``` The import statements above are divided into three distinct groups, separated by a blank space. They are also ordered alphabetically within each group. [Remove ads](https://realpython.com/account/join/) ## Absolute Imports You’ve gotten up to speed on how to write import statements and how to style them like a pro. Now it’s time to learn a little more about absolute imports. An absolute import specifies the resource to be imported using its full path from the project’s root folder. ### Syntax and Practical Examples Let’s say you have the following directory structure: Shell ``` ``` There’s a directory, `project`, which contains two sub-directories, `package1` and `package2`. The `package1` directory has two files, `module1.py` and `module2.py`. The `package2` directory has three files: two modules, `module3.py` and `module4.py`, and an initialization file, `__init__.py`. It also contains a directory, `subpackage`, which in turn contains a file, `module5.py`. Let’s assume the following: 1. `package1/module2.py` contains a function, `function1`. 2. `package2/__init__.py` contains a class, `class1`. 3. `package2/subpackage1/module5.py` contains a function, `function2`. The following are practical examples of absolute imports: Python ``` ``` Note that you must give a detailed path for each package or file, from the top-level package folder. This is somewhat similar to its file path, but we use a dot (`.`) instead of a slash (`/`). ### Pros and Cons of Absolute Imports Absolute imports are preferred because they are quite clear and straightforward. It is easy to tell exactly where the imported resource is, just by looking at the statement. Additionally, absolute imports remain valid even if the current location of the import statement changes. In fact, PEP 8 explicitly recommends absolute imports. Sometimes, however, absolute imports can get quite verbose, depending on the complexity of the directory structure. Imagine having a statement like this: Python ``` from package1.subpackage2.subpackage3.subpackage4.module5 import function6 ``` That’s ridiculous, right? Luckily, relative imports are a good alternative in such cases\! ## Relative Imports A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won’t be covering them here. [Remove ads](https://realpython.com/account/join/) ### Syntax and Practical Examples The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported. Here are a few examples of relative imports: Python ``` ``` You can see that there is at least one dot in each import statement above. Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above. Three dots mean that it is in the grandparent directory, and so on. This will probably be familiar to you if you use a Unix-like operating system\! Let’s assume you have the same directory structure as before: Shell ``` ``` Recall the file contents: 1. `package1/module2.py` contains a function, `function1`. 2. `package2/__init__.py` contains a class, `class1`. 3. `package2/subpackage1/module5.py` contains a function, `function2`. You can import `function1` into the `package1/module1.py` file this way: Python ``` ``` You’d use only one dot here because `module2.py` is in the same directory as the current module, which is `module1.py`. You can import `class1` and `function2` into the `package2/module3.py` file this way: Python ``` ``` In the first import statement, the single dot means that you are importing `class1` from the current package. Remember that importing a package essentially imports the package’s `__init__.py` file as a module. In the second import statement, you’d use a single dot again because `subpackage1` is in the same directory as the current module, which is `module3.py`. ### Pros and Cons of Relative Imports One clear advantage of relative imports is that they are quite succinct. Depending on the current location, they can turn the ridiculously long import statement you saw earlier to something as simple as this: Python ``` from ..subpackage4.module5 import function6 ``` Unfortunately, relative imports can be messy, particularly for shared projects where directory structure is likely to change. Relative imports are also not as readable as absolute ones, and it’s not easy to tell the location of the imported resources. [Remove ads](https://realpython.com/account/join/) ## Conclusion Good job for making it to the end of this crash course on absolute and relative imports! Now you’re up to speed on how imports work. You’ve learned the best practices for writing import statements, and you know the difference between absolute and relative imports. With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long. Thanks for reading\! Mark as Completed Share Recommended Course [Absolute vs Relative Imports in Python](https://realpython.com/courses/absolute-vs-relative-imports-python/) (16m) 🐍 Python Tricks 💌 Get a short & sweet **Python Trick** delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. ![Python Tricks Dictionary Merge](https://realpython.com/static/pytrick-dict-merge.4201a0125a5e.png) About **Mbithe Nzomo** [![Mbithe Nzomo](https://realpython.com/cdn-cgi/image/width=500,height=500,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/mbithe.d732891331d8.jpg) ![Mbithe Nzomo](https://realpython.com/cdn-cgi/image/width=500,height=500,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/mbithe.d732891331d8.jpg)](https://realpython.com/team/mnzomo/) I'm an experienced software engineer with interests in artificial intelligence and machine learning. I'm currently a postgraduate student at The University of Manchester, studying Advanced Computer Science with a specialisation in AI. [» More about Mbithe](https://realpython.com/team/mnzomo/) *** *Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:* [![Adriana Cutenco](https://realpython.com/cdn-cgi/image/width=900,height=900,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/acutenco.676e4197c133.jpg)](https://realpython.com/team/acutenco/) [Adriana](https://realpython.com/team/acutenco/) [![David Amos](https://realpython.com/cdn-cgi/image/width=400,height=400,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/me-small.f5f49f1c48e1.jpg)](https://realpython.com/team/damos/) [David](https://realpython.com/team/damos/) [![Joanna Jablonski](https://realpython.com/cdn-cgi/image/width=800,height=800,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/jjablonksi-avatar.e37c4f83308e.jpg)](https://realpython.com/team/jjablonski/) [Joanna](https://realpython.com/team/jjablonski/) Master Real-World Python Skills With Unlimited Access to Real Python ![Locked learning resources](https://realpython.com/static/videos/lesson-locked.f5105cfd26db.svg) **Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:** [Level Up Your Python Skills »](https://realpython.com/account/join/?utm_source=rp_article_footer&utm_content=absolute-vs-relative-python-imports) Master Real-World Python Skills With Unlimited Access to Real Python ![Locked learning resources](https://realpython.com/static/videos/lesson-locked.f5105cfd26db.svg) **Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:** [Level Up Your Python Skills »](https://realpython.com/account/join/?utm_source=rp_article_footer&utm_content=absolute-vs-relative-python-imports) What Do You Think? **Rate this article:** [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Frealpython.com%2Fabsolute-vs-relative-python-imports%2F) [Twitter](https://twitter.com/intent/tweet/?text=Interesting%20Python%20article%20on%20%40realpython%3A%20Absolute%20vs%20Relative%20Imports%20in%20Python&url=https%3A%2F%2Frealpython.com%2Fabsolute-vs-relative-python-imports%2F) [Bluesky](https://bsky.app/intent/compose?text=Interesting%20Python%20article%20on%20%40realpython.com%3A%20Absolute%20vs%20Relative%20Imports%20in%20Python%20https%3A%2F%2Frealpython.com%2Fabsolute-vs-relative-python-imports%2F) [Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Frealpython.com%2Fabsolute-vs-relative-python-imports%2F) [Email](mailto:?subject=Python%20article%20for%20you&body=Absolute%20vs%20Relative%20Imports%20in%20Python%20on%20Real%20Python%0A%0Ahttps%3A%2F%2Frealpython.com%2Fabsolute-vs-relative-python-imports%2F%0A) What’s your \#1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. **Commenting Tips:** The most useful comments are those written with the goal of learning from or helping out other students. [Get tips for asking good questions](https://realpython.com/python-beginner-tips/#tip-9-ask-good-questions) and [get answers to common questions in our support portal](https://support.realpython.com/). *** Looking for a real-time conversation? Visit the [Real Python Community Chat](https://realpython.com/community/) or join the next [“Office Hours” Live Q\&A Session](https://realpython.com/office-hours/). Happy Pythoning\! Keep Learning Related Topics: [intermediate](https://realpython.com/tutorials/intermediate/) [best-practices](https://realpython.com/tutorials/best-practices/) [python](https://realpython.com/tutorials/python/) Related Learning Paths: - [Modules and Packages](https://realpython.com/learning-paths/modules-and-packages/?utm_source=realpython&utm_medium=web&utm_campaign=related-learning-path&utm_content=absolute-vs-relative-python-imports) Related Courses: - [Absolute vs Relative Imports in Python](https://realpython.com/courses/absolute-vs-relative-imports-python/?utm_source=realpython&utm_medium=web&utm_campaign=related-course&utm_content=absolute-vs-relative-python-imports) Related Tutorials: - [Python import: Advanced Techniques and Tips](https://realpython.com/python-import/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=absolute-vs-relative-python-imports) - [Python Modules and Packages – An Introduction](https://realpython.com/python-modules-packages/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=absolute-vs-relative-python-imports) - [What's a Python Namespace Package, and What's It For?](https://realpython.com/python-namespace-package/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=absolute-vs-relative-python-imports) - [What Is Python's \_\_init\_\_.py For?](https://realpython.com/python-init-py/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=absolute-vs-relative-python-imports) - [Python Type Checking (Guide)](https://realpython.com/python-type-checking/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=absolute-vs-relative-python-imports) ## Keep reading Real Python by creating a free account or signing in: [![Keep reading](https://realpython.com/static/videos/lesson-locked.f5105cfd26db.svg)](https://realpython.com/account/signup/?intent=continue_reading&utm_source=rp&utm_medium=web&utm_campaign=rwn&utm_content=v1&next=%2Fabsolute-vs-relative-python-imports%2F) [Continue »](https://realpython.com/account/signup/?intent=continue_reading&utm_source=rp&utm_medium=web&utm_campaign=rwn&utm_content=v1&next=%2Fabsolute-vs-relative-python-imports%2F) Already have an account? [Sign-In](https://realpython.com/account/login/?next=/absolute-vs-relative-python-imports/) Almost there! Complete this form and click the button below to gain instant access: × ![Python Logo](https://files.realpython.com/media/python-logo.8eb72ea6927b.png) 5 Thoughts On Python Mastery ##### Learn Python - [Start Here](https://realpython.com/start-here/) - [Learning Resources](https://realpython.com/search) - [Code Mentor](https://realpython.com/mentor/) - [Python Reference](https://realpython.com/ref/) - [Python Cheat Sheet](https://realpython.com/cheatsheets/python/) - [Support Center](https://support.realpython.com/) ##### Courses & Paths - [Learning Paths](https://realpython.com/learning-paths/) - [Quizzes & Exercises](https://realpython.com/quizzes/) - [Browse Topics](https://realpython.com/tutorials/all/) - [Live Courses](https://realpython.com/live/) - [Books](https://realpython.com/books/) ##### Community - [Podcast](https://realpython.com/podcasts/rpp/) - [Newsletter](https://realpython.com/newsletter/) - [Community Chat](https://realpython.com/community/) - [Office Hours](https://realpython.com/office-hours/) - [Learner Stories](https://realpython.com/learner-stories/) ##### Membership - [Plans & Pricing](https://realpython.com/account/join/) - [Team Plans](https://realpython.com/account/join-team/) - [For Business](https://realpython.com/account/join-team/inquiry/) - [For Schools](https://realpython.com/account/join-team/education-inquiry/) - [Reviews](https://realpython.com/learner-stories/) ##### Company - [About Us](https://realpython.com/about/) - [Team](https://realpython.com/team/) - [Mission & Values](https://realpython.com/mission/) - [Editorial Guidelines](https://realpython.com/editorial-guidelines/) - [Sponsorships](https://realpython.com/sponsorships/) - [Careers](https://realpython.workable.com/) - [Press Kit](https://realpython.com/media-kit/) - [Merch](https://realpython.com/merch) [Privacy Policy](https://realpython.com/privacy-policy/) ⋅ [Terms of Use](https://realpython.com/terms/) ⋅ [Security](https://realpython.com/security/) ⋅ [Contact](https://realpython.com/contact/) Happy Pythoning\! © 2012–2026 DevCademy Media Inc. DBA Real Python. All rights reserved. REALPYTHONℱ is a trademark of DevCademy Media Inc. [![Real Python - Online Python Training (logo)](https://realpython.com/static/real-python-logo-primary.973743b6d39d.svg)](https://realpython.com/) ![](https://www.facebook.com/tr?id=2220911568135371&ev=PageView&noscript=1) You've blocked notifications
Readable Markdown
If you’ve worked on a Python project that has more than one file, chances are you’ve had to use an import statement before. Even for Pythonistas with a couple of projects under their belt, imports can be confusing! You’re probably reading this because you’d like to gain a deeper understanding of imports in Python, particularly absolute and relative imports. In this tutorial, you’ll learn the differences between the two, as well as their pros and cons. Let’s dive right in\! ## A Quick Recap on Imports You need to have a good understanding of [Python modules and packages](https://realpython.com/python-modules-packages/) to know how imports work. A Python module is a file that has a `.py` extension, and a Python package is any folder that has modules inside it (or, in Python 2, a folder that contains an `__init__.py` file). What happens when you have code in one module that needs to access code in another module or package? You import it\! ### How Imports Work But how exactly do imports work? Let’s say you import a module `abc` like so: The first thing Python will do is look up the name `abc` in [`sys.modules`](https://docs.python.org/3/library/sys.html#sys.modules). This is a cache of all modules that have been previously imported. If the name isn’t found in the module cache, Python will proceed to search through a list of built-in modules. These are modules that come pre-installed with Python and can be found in the [Python Standard Library](https://docs.python.org/3/library/). If the name still isn’t found in the built-in modules, Python then searches for it in a list of directories defined by [`sys.path`](https://docs.python.org/3/library/sys.html#sys.path). This list usually includes the current directory, which is searched first. When Python finds the module, it binds it to a name in the local scope. This means that `abc` is now defined and can be used in the current file without throwing a `NameError`. If the name is never found, you’ll get a `ModuleNotFoundError`. You can find out more about imports in the Python documentation [here](https://docs.python.org/3/reference/import.html)\! ### Syntax of Import Statements Now that you know how import statements work, let’s explore their syntax. You can import both packages and modules. (Note that importing a package essentially imports the package’s `__init__.py` file as a module.) You can also import specific objects from a package or module. There are generally two types of import syntax. When you use the first one, you import the resource directly, like this: `abc` can be a package or a module. When you use the second syntax, you import the resource from another package or module. Here’s an example: `xyz` can be a module, subpackage, or object, such as a class or function. You can also choose to rename an imported resource, like so: This renames the imported resource `abc` to `other_name` within the script. It must now be referenced as `other_name`, or it will not be recognized. ### Styling of Import Statements [PEP 8](http://pep8.org/#imports), the official [style guide for Python](https://realpython.com/python-code-quality/), has a few pointers when it comes to writing import statements. Here’s a summary: 1. Imports should always be written at the top of the file, after any module comments and [docstrings](https://realpython.com/how-to-write-docstrings-in-python/). 2. Imports should be divided according to what is being imported. There are generally three groups: - standard library imports (Python’s built-in modules) - related third party imports (modules that are installed and do not belong to the current application) - local application imports (modules that belong to the current application) 3. Each group of imports should be separated by a blank line. It’s also a good idea to order your imports alphabetically within each import group. This makes finding particular imports much easier, especially when there are many imports in a file. Here’s an example of how to style import statements: The import statements above are divided into three distinct groups, separated by a blank space. They are also ordered alphabetically within each group. ## Absolute Imports You’ve gotten up to speed on how to write import statements and how to style them like a pro. Now it’s time to learn a little more about absolute imports. An absolute import specifies the resource to be imported using its full path from the project’s root folder. ### Syntax and Practical Examples Let’s say you have the following directory structure: There’s a directory, `project`, which contains two sub-directories, `package1` and `package2`. The `package1` directory has two files, `module1.py` and `module2.py`. The `package2` directory has three files: two modules, `module3.py` and `module4.py`, and an initialization file, `__init__.py`. It also contains a directory, `subpackage`, which in turn contains a file, `module5.py`. Let’s assume the following: 1. `package1/module2.py` contains a function, `function1`. 2. `package2/__init__.py` contains a class, `class1`. 3. `package2/subpackage1/module5.py` contains a function, `function2`. The following are practical examples of absolute imports: Note that you must give a detailed path for each package or file, from the top-level package folder. This is somewhat similar to its file path, but we use a dot (`.`) instead of a slash (`/`). ### Pros and Cons of Absolute Imports Absolute imports are preferred because they are quite clear and straightforward. It is easy to tell exactly where the imported resource is, just by looking at the statement. Additionally, absolute imports remain valid even if the current location of the import statement changes. In fact, PEP 8 explicitly recommends absolute imports. Sometimes, however, absolute imports can get quite verbose, depending on the complexity of the directory structure. Imagine having a statement like this: That’s ridiculous, right? Luckily, relative imports are a good alternative in such cases\! ## Relative Imports A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won’t be covering them here. ### Syntax and Practical Examples The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported. Here are a few examples of relative imports: You can see that there is at least one dot in each import statement above. Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above. Three dots mean that it is in the grandparent directory, and so on. This will probably be familiar to you if you use a Unix-like operating system\! Let’s assume you have the same directory structure as before: Recall the file contents: 1. `package1/module2.py` contains a function, `function1`. 2. `package2/__init__.py` contains a class, `class1`. 3. `package2/subpackage1/module5.py` contains a function, `function2`. You can import `function1` into the `package1/module1.py` file this way: You’d use only one dot here because `module2.py` is in the same directory as the current module, which is `module1.py`. You can import `class1` and `function2` into the `package2/module3.py` file this way: In the first import statement, the single dot means that you are importing `class1` from the current package. Remember that importing a package essentially imports the package’s `__init__.py` file as a module. In the second import statement, you’d use a single dot again because `subpackage1` is in the same directory as the current module, which is `module3.py`. ### Pros and Cons of Relative Imports One clear advantage of relative imports is that they are quite succinct. Depending on the current location, they can turn the ridiculously long import statement you saw earlier to something as simple as this: Unfortunately, relative imports can be messy, particularly for shared projects where directory structure is likely to change. Relative imports are also not as readable as absolute ones, and it’s not easy to tell the location of the imported resources. ## Conclusion Good job for making it to the end of this crash course on absolute and relative imports! Now you’re up to speed on how imports work. You’ve learned the best practices for writing import statements, and you know the difference between absolute and relative imports. With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long. Thanks for reading\!
ML Classification
ML Categories
/Computers_and_Electronics
98.8%
/Computers_and_Electronics/Programming
95.6%
/Computers_and_Electronics/Programming/Scripting_Languages
92.2%
Raw JSON
{
    "/Computers_and_Electronics": 988,
    "/Computers_and_Electronics/Programming": 956,
    "/Computers_and_Electronics/Programming/Scripting_Languages": 922
}
ML Page Types
/Article
99.9%
/Article/Tutorial_or_Guide
99.3%
Raw JSON
{
    "/Article": 999,
    "/Article/Tutorial_or_Guide": 993
}
ML Intent Types
Informational
99.9%
Raw JSON
{
    "Informational": 999
}
Content Metadata
Languageen
AuthorReal Python
Publish Timenot set
Original Publish Time2018-09-19 14:56:36 (7 years ago)
RepublishedNo
Word Count (Total)2,566
Word Count (Content)1,412
Links
External Links23
Internal Links95
Technical SEO
Meta NofollowNo
Meta NoarchiveNo
JS RenderedYes
Redirect Targetnull
Performance
Download Time (ms)214
TTFB (ms)190
Download Size (bytes)20,807
Shard71 (laksa)
Root Hash13351397557425671
Unparsed URLcom,realpython!/absolute-vs-relative-python-imports/ s443