Concepts / Importing Specific Functions from Modules

Importing Specific Functions from Modules

When you import a specific function, the purpose is to make that function available to the importing program rather than requiring the program to work with every module name at once.

  • Programming
Interactive lab

Try it: What import Really Does

What happens on import: Python checks sys.modules, searches sys.path in order (first match wins), creates the module object, runs its top level once, then binds a name — the module, one function, or an alias — in the importing namespace; plus packages, __name__ == "__main__", ModuleNotFoundError and ImportError.

How it works

  1. If the name is already in sys.modules, reuse that module object: its code does not run again.
  2. Otherwise search each sys.path entry in order (the script's folder first); the first match wins, none raises ModuleNotFoundError.
  3. Create an empty module object, store it in sys.modules, then run the file's top level once (its __name__ is the module name, so a __main__ guard is skipped).
  4. import m binds m to the module; import m as x binds x; from m import f binds only f (ImportError if m has no f).
  5. A package runs its __init__.py first; submodules are found on the package's __path__ and become attributes of the package.

Default run (19 steps): $ python main.py — sys.path starts as [/project, /venv/site-packages, /usr/lib/python3.12]: the script's folder, then site-packages, then the standard library. Only our own modules are shown in sys.modules below. … Done. Printed: helpers loaded, __name__ = helpers | Hi Ann | Hi Ann.

Simplified: A fixed virtual project (main.py, helpers.py, pkg/, a site-packages folder and a one-file stand-in for the standard library). Built-in and frozen modules, .pyc caching, relative imports and namespace packages are not modelled; only our own modules are listed in sys.modules.

Educational simulation

Loading the simulation…

An Import Starts a Process

An import statement is an instruction to Python to locate a module, load it, execute the code in that module, and make its contents available to your program. This is more than declaring a variable or defining a function: Python begins a search-and-execute process behind the scenes.

Key point

When you import a specific function, the purpose is to make that function available to the importing program rather than requiring the program to work with every module name at once.

The Import Sequence

import statementSearch directoriessys.pathModule filefirst matching fileModule codeexecuteModule contentsavailable to the programrequestsfindsloadsexposes
What happens after Python encounters an import statement, from locating the module to making its contents available?

The sequence has four important stages. Python first receives the import request. It then searches for the requested module. After finding a matching file or compiled version, it loads and executes the module's code. Finally, the module's contents become available to the importing program. Importing a specific function follows the same module-loading process; the difference is that the program asks for a particular function from the module's contents.

Worked example

Tracing a Specific Function Import

Suppose a program requests one function from a module.

  1. 1
    Request

    The import statement identifies a module and a specific function that the program wants to use.

  2. 2
    Locate

    Python searches for the module using its module-search process.

  3. 3
    Initialize

    Python loads the module and executes the code in its body.

  4. 4
    Make available

    The requested function is made available to the importing program as part of the module's contents.

Result

The function becomes available only after Python has located and initialized its module.

The Search Path

For a module that is not built into Python, Python searches directories listed in sys.path. The directories are checked in a specific order, and Python stops when it finds the first matching module file. This order determines which file is selected when more than one searchable directory could contain a matching name.

Requested moduleDirectory 1first sys.path entryDirectory 2next sys.path entryDirectory 3later sys.path entryFirst matchmodule filecheck firstif no matchif no matchstop at match
How does Python use sys.path to locate the requested module?

You can think of sys.path as an ordered set of breadcrumbs. Python walks through the directories one at a time, looking for a file whose name matches the requested module. The directory containing the running script is typically checked first. Standard library directories and site-packages are also among the locations Python may search. The exact list can be inspected by printing sys.path after importing sys.

One-Time Initialization

Python executes a module's body only the first time that module is imported. After the module has been loaded, Python caches it in memory. Later imports of the same module reuse the cached module instead of executing its initialization code again.

Module not loadedFirst importexecute module codeCached moduleloaded in memoryLater importreuse cached moduleimportinitializereuse
What changes after the first import so later imports reuse the module instead of executing its code again?

The important change is the module's status: before the first import, Python must locate and initialize it; after the first import, the initialized module is cached. A later import therefore returns the cached version without re-running the module's initialization code. This avoids the overhead of re-executing the module and re-creating its variables and functions.

Modulecontains functionsSpecific functionrequested contentImporting programfunction available herecontainsmade available
Where does the requested function appear in the importing program, and what does the imported name refer to?

Specific Function Imports

The specific-function form asks Python to make one named function from a module available to the importing program. The module still has to be located, loaded, and initialized first. Importing one function does not skip the module search or the module's initialization process; it identifies which part of the module's contents the program intends to use.

frommodule sourcemodulemodule to locateimportrequest contentsfunctionspecific content
How does the specific-function import form identify the module and the function to make available?
Worked example

Separating the Two Names

Read a specific-function import as a request involving a module name and a function name.

  1. 1
    Module name

    The module name tells Python which module it must locate through its import process.

  2. 2
    Function name

    The function name identifies the particular function from that module that the importing program wants available.

  3. 3
    Initialization

    Python still executes the module's code the first time the module is imported.

  4. 4
    Reuse

    If the module has already been initialized, Python reuses the cached module instead of executing its code again.

Result

A specific-function import narrows which module content the program requests, but it does not remove the module-location and initialization steps.

Mistakes to Avoid

  • Common mistake

    Assuming an import only retrieves an already available object.

    What it looks like

    Treating an import as if it were merely a variable declaration.

    Why it fails

    Python may need to search for the module, load it, execute its code, and make its contents available.

    Do this instead

    Trace the full process: search, load, execute, and expose the module contents.

  • Common mistake

    Assuming Python searches every directory after finding a match.

    What it looks like

    Expecting a later directory in sys.path to replace the first matching module.

    Why it fails

    Python searches directories in order and stops at the first match.

    Do this instead

    Check the order of sys.path when investigating which module Python may locate.

  • Common mistake

    Expecting a module to reinitialize every time it is imported.

    What it looks like

    Expecting initialization code or module state to be recreated by a later import.

    Why it fails

    The module is cached after its first import, and later imports reuse it without re-executing its code.

    Do this instead

    Treat module initialization as a one-time process during the program's execution.

  • Common mistake

    Ignoring naming conflicts.

    What it looks like

    Creating a file with the same name as a standard library module.

    Why it fails

    The search order in sys.path can cause Python to find the local file instead of the expected module.

    Do this instead

    Use module names carefully and consider sys.path order when debugging unexpected imports.

Best practice

When an import behaves unexpectedly, ask three questions: Which module name did the statement request? Which directories appear in sys.path and in what order? Has the module already been initialized and cached? These questions connect the visible import statement to Python's search, execution, and reuse behavior.

Trace the Process

MEDIUM

A program imports one function from a module, and later another statement imports the same module. Describe the sequence of events for the first import and explain what changes during the later import.

Hints
  • Start with the directories in sys.path.
  • Identify when the module's code runs.
  • Explain what Python reuses after the first import.
  1. 1
    An import statement triggers a search, load, execution, and availability process.
  2. 2
    Python searches directories in sys.path in order and stops at the first matching module.
  3. 3
    The first import executes the module's initialization code and caches the loaded module.
  4. 4
    Later imports reuse the cached module without re-executing its initialization code.
  5. 5
    Importing a specific function identifies one requested part of a module, but the module still must be located and initialized.

Key Takeaways

  • Importing is an active search-and-execute process, not merely a variable declaration.
  • sys.path controls the ordered directory search for non-built-in modules.
  • Python stops at the first matching module file it finds.
  • A module's code runs once on first import, then the cached module is reused.
  • A specific-function import requests one function from a module while still relying on the module's normal loading process.

Related concepts

More concepts starting with I