Concepts / How to Import Modules in Python

How to Import Modules in Python

How It Works First, we import the sys module using the import statement. Basically, this translates to us telling Python that we want to use this module. The sys module contains functionality related to the Python interpreter and its environment i.e. the sys tem.

  • Programming

What Happens When You Import

When you write import sys at the start of your Python script, you are telling Python: I want to use the functionality from the sys module. But what actually happens inside Python is more interesting than just that request. Python does not instantly hand you access to everything in the module. Instead, it follows a specific sequence: it searches for the module, loads it if it has not been loaded before, runs all the code in that module, and then makes it available to you under a name in your current namespace.

The initialization of a module happens only the first time you import it. If you import the same module again in the same Python session, Python does not re-run the module's code; it simply reuses the already-loaded module.

The Import Search Process

When Python encounters an import statement, it does not search randomly. It follows a specific order, checking directories in a particular sequence. This sequence is stored in a special variable called sys.path, which is a list of directory names where Python looks for modules.

The sys.path list always begins with an empty string. This empty string is special: it represents the current directory, the directory where your script is running. This means you can immediately import any Python file that is in the same folder as your script without having to do anything extra. After the current directory, Python searches through all the other directories listed in sys.path in order.

yesnofoundnot foundfoundnot foundimport mymoduleIs it a built-inmodule?Load built-in moduleCurrent directory(empty string insys.path)Module found andloadedSearch sys.pathdirectoriesOther directories insys.pathModuleNotFoundError
When you write 'import mymodule', where does Python look and in what order?

Built-in modules like sys, os, and math are handled specially. Python knows where these are stored because they come with Python itself, so it does not need to search your directories. For modules you write yourself or install from third parties, Python searches through sys.path in order. If the module is found in any of those directories, it is loaded. If Python searches through all of sys.path and does not find the module, you get a ModuleNotFoundError.

Import Syntax and Namespace Effects

Python offers different ways to import modules, and each one puts different things into your namespace. Understanding these differences is crucial because they change how you access the module's contents in your code.

import sysYour namespacecontains: sysAccess as: sys.path,sys.versionimport syssys (the moduleobject)module objectsys.path, sys.versionfrom sys importpathYour namespacecontains: pathAccess as: path(directly)from sys importpathpath (a list)the actual list objectpath (use directly)
What ends up in your namespace and how do you call it for each import style?

When you use import sys, Python places the module object itself into your namespace under the name sys. To access anything from that module, you must use dot notation: sys.path, sys.version, sys.exit, and so on. The module name becomes a gateway to everything inside it.

When you use from sys import path, Python extracts the specific item (in this case, the path list) from the sys module and places it directly into your namespace. You can then use path without any prefix. This is more direct but also more selective: you only get what you explicitly ask for.

Understanding sys.path

The sys.path variable is a list of strings, where each string is a directory path. When you import a module, Python walks through this list in order, checking each directory to see if the module file exists there. The first element in sys.path is always an empty string, which represents the current working directory.

The empty string at the start of sys.path means you can import any Python file from the same directory as your script without any special setup. This is why you can write import mymodule if mymodule.py is in the same folder.

If you want to import a module from a different directory, you have two choices. First, you can move the module file into one of the directories already in sys.path. Second, you can add a new directory to sys.path before importing. This is often done at the top of a script using sys.path.append() or sys.path.insert().

How the Import Mechanism Works Inside Python

import sysSearch for sys moduleModule file locatedExecute module codeCreate module objectStore in sys.modulescacheYou can now usesys.path, sys.exit,etc.Bind name 'sys' inyour namespace
Where does the module go in memory and how do you access it after import?

Here is the detailed sequence. First, Python searches for the module using sys.path. Once found, Python executes all the code in that module file. This execution creates functions, classes, and variables that are part of the module. Python then wraps all of this into a module object. This object is stored in a special cache called sys.modules so that if you import the same module again, Python can reuse it without re-executing the code. Finally, Python binds the name sys (or whatever name you specified) to this module object in your current namespace, making it accessible to your code.

Worked Example: Importing and Using a Module

Importing the sys module and accessing its contents

You want to import the sys module and find out what version of Python is running, and also see the list of directories where Python searches for modules.

Write the import statement: Start by importing the sys module. This tells Python to load the sys module and make it available in your namespace.

Access sys.version: Use sys.version to get a string describing the Python version. Since you imported the module as sys, you must use the dot notation to access its contents.

Access sys.path: Use sys.path to see the list of directories. The first element will be an empty string (the current directory), followed by system directories where Python looks for modules.

Understand the output: sys.version returns a long string with version and build information. sys.path returns a list of directory paths. The empty string at index 0 means your current directory is always searched first.

After executing import sys, you can call sys.version to see the Python version and sys.path to see where Python searches for modules. The module object sys is now in your namespace and remains there for the rest of your script.

Common Mistakes When Importing

  • Using from sys import * and then trying to access sys.path

    The from X import * syntax imports all public names from the module into your namespace, but it does not import the module object itself. You get the individual items (like path, version, exit) but not the module container.

    Fix: Either use import sys and then sys.path, or use from sys import path and then just path. Do not mix the two styles.

  • Assuming a module in your current directory will always be found

    This can happen if your current working directory is not what you think it is. Python searches the directory where your script is running, but if you run the script from a different directory, the current directory in sys.path might not be the same.

    Fix: Check your current working directory with os.getcwd() or verify that sys.path[0] is empty (which represents the current directory). Run your script from the directory containing it, or add the correct path to sys.path explicitly.

  • Forgetting that module initialization happens only once per session

    Python caches modules in sys.modules. When you import a module a second time, Python does not re-read the file; it reuses the cached version.

    Fix: Restart your Python interpreter to reload the module, or use the importlib.reload() function if you need to reload a module within the same session.

  • Writing import sys.path instead of from sys import path

    The import statement expects a module name, not an attribute of a module. sys.path is not a module; it is a list inside the sys module.

    Fix: Use import sys and then access sys.path, or use from sys import path to import just the path list.

Best Practices for Importing

  • Place all import statements at the top of your file, before any other code. This makes it clear what dependencies your script has.
  • Use import modulename for modules you will use multiple times throughout your code. The dot notation makes it clear where each function or variable comes from.
  • Use from modulename import specificname only when you are importing a single, well-known item that you will use frequently. This reduces typing but can make code less clear about where things come from.
  • Avoid from modulename import * in production code. It pollutes your namespace and makes it hard to see where functions come from. It is acceptable in interactive sessions for exploration.
  • If you need to import a module from a non-standard location, add that location to sys.path at the very top of your script, before any other imports.
  • Use meaningful import names. If you import a module with a long name, you can use import longmodulename as short to create an alias, but keep the alias clear and related to the original name.

Practice: Predict and Verify

What do you think happens?

You write the following code: from os import path; print(path). What will be printed?

  • An error because path is not a module
  • A path object or string representing a file system path
  • The os module object
  • An error because you cannot import path from os
Reveal answer

Answer: A path object or string representing a file system path

The from os import path statement extracts the path submodule from os and places it in your namespace. When you print(path), you are printing the os.path object, which is a module that provides path manipulation functions. The key insight is that from X import Y puts Y directly into your namespace, not X.

EASY

Write a short Python script that imports the sys module and prints the first three directories in sys.path. What do you notice about the first entry?

Hints
  • Use import sys to load the module.
  • Access sys.path to get the list of directories.
  • Use list slicing (sys.path[:3]) to get the first three entries.
  • The first entry is likely an empty string, which represents the current directory.

Summary

Importing a module in Python is a multi-step process that happens behind the scenes. When you write import sys, Python searches for the module (checking built-in modules first, then directories in sys.path), executes the module code, creates a module object, caches it, and binds the name to your namespace. Different import styles (import X versus from X import Y) result in different things appearing in your namespace and different ways of accessing them. The sys.path list controls where Python searches, with the current directory always first. Understanding this mechanism helps you troubleshoot import errors and write clearer, more maintainable code.

Key Takeaways

  • When you execute import sys, Python searches for the module, loads it (only on first import), executes its code, and binds the module object to your namespace.
  • Python searches for modules in a specific order: built-in modules first, then directories listed in sys.path, starting with the current directory (represented by an empty string).
  • import modulename places the module object in your namespace; you access its contents with dot notation (modulename.attribute). from modulename import name places only that specific name in your namespace.
  • The sys.path list determines where Python looks for modules. You can modify it to import modules from non-standard locations.
  • Module initialization happens only once per Python session; subsequent imports reuse the cached module from sys.modules.