Skip to content

How to Access and Import Functions in Python Modules

Learn how to import Python modules and access their functions using dot notation, specific imports, aliases, and dynamic loading techniques while avoiding common pitfalls like namespace collisions.

In Python, a module is simply a file containing Python code (functions, classes, or variables). Accessing these functions efficiently is key to organizing code into reusable components. Whether you are using Python's built-in libraries (like math or os) or your own custom files, the import statement is the bridge between them.

This guide explains the different syntaxes for importing modules, how to resolve scope issues, and advanced techniques for dynamic loading.

Prerequisites: Creating a Module

To understand how to access functions, let's first simulate a custom module. Imagine you have a file named math_operations.py in your current directory.

File: math_operations.py

PI = 3.14159

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

We will use this file in the examples below.

Method 1: Full Module Import (Dot Notation)

The most standard way to access a module is using the import keyword followed by the filename (without .py). This imports the entire module object. To access functions inside it, you must use dot notation (module.function).

import math_operations

result = math_operations.add(5, 3)
print(f"Result: {result}")

print(f"Pi is: {math_operations.PI}")

try:
    print(add(5, 3))
except NameError as e:
    print(f"Error: {e}")

Output:

Result: 8
Pi is: 3.14159
Error: name 'add' is not defined

Method 2: Importing Specific Functions

If you only need a specific function and don't want to type the module name every time, use the from ... import ... syntax. This brings the function directly into your current global namespace.

from math_operations import add, PI

sum_val = add(10, 5)
print(f"Sum: {sum_val}")
print(f"Pi: {PI}")

try:
    print(multiply(2, 3))
except NameError as e:
    print(f"Error: {e}")

Output:

Sum: 15
Pi: 3.14159
Error: name 'multiply' is not defined

Method 3: Using Aliases

If a module name is long or conflicts with an existing variable name, you can rename it during import using the as keyword.

Aliasing a Module

import math_operations as mo

print(f"Multiplication: {mo.multiply(4, 4)}")

Aliasing a Function

from math_operations import add as addition

print(f"Addition: {addition(1, 1)}")

Advanced: Dynamic and Conditional Imports

Sometimes you don't know the module name until runtime, or you need to import different modules based on the operating system.

Conditional Imports

Useful for cross-platform compatibility.

import sys

if sys.platform.startswith('linux'):
    print("Loaded Linux specific functions")
elif sys.platform.startswith('win'):
    print("Loaded Windows specific functions")

Dynamic Imports using importlib

If the module name is stored in a string variable, you cannot use the standard import statement. Use importlib.

import importlib

module_name = 'math_operations'

mod = importlib.import_module(module_name)

result = mod.subtract(10, 2) if hasattr(mod, 'subtract') else "Function not found"
print(f"Dynamic import result: {mod.add(10, 10)}")

Output:

Dynamic import result: 20

Best Practices and Anti-Patterns

The Wildcard Import (*)

You can import everything from a module using from module import *. However, this is generally discouraged in production code.

from math_operations import *

print(add(1, 2))

Handling ImportError

Always handle potential missing modules gracefully, especially when using third-party libraries.

try:
    import non_existent_module
except ImportError:
    print("Module not found. Using fallback logic...")

Conclusion

Accessing module functions is a balance between readability and convenience.

  1. Use import module for clarity and to avoid naming conflicts.
  2. Use from module import func for frequently used functions.
  3. Use as alias to shorten long names.
  4. Avoid from module import * to keep your namespace clean.
Navigation