Skip to main content

How to Access and Import Functions in Python Modules

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

# This is our custom module
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

# ✅ Correct: Access function via module name
result = math_operations.add(5, 3)
print(f"Result: {result}")

# ✅ Correct: Access variable via module name
print(f"Pi is: {math_operations.PI}")

try:
# ⛔️ Incorrect: Trying to call the function directly without the prefix
# Python does not know what 'add' is in the current scope
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
note

This method is safest because it prevents namespace collisions. If you have a function named add in your main script, it won't conflict with math_operations.add.

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.

# Import only the 'add' function and 'PI' constant
from math_operations import add, PI

# ✅ Correct: Call the function directly
sum_val = add(10, 5)
print(f"Sum: {sum_val}")
print(f"Pi: {PI}")

try:
# ⛔️ Incorrect: The module itself is NOT imported, only the specific items
# You cannot access other functions like 'multiply'
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

# ✅ Correct: Use the short alias
print(f"Multiplication: {mo.multiply(4, 4)}")

Aliasing a Function

from math_operations import add as addition

# ✅ Correct: Use the renamed function
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

# Check platform and import correspondingly
if sys.platform.startswith('linux'):
# import linux_module (Hypothetical)
print("Loaded Linux specific functions")
elif sys.platform.startswith('win'):
# import windows_module (Hypothetical)
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'

# Dynamically load the module
mod = importlib.import_module(module_name)

# Use it just like a standard import
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.

# ⚠️ Anti-Pattern: Wildcard Import
from math_operations import *

# It works, but...
print(add(1, 2))
warning

Avoid Wildcard Imports: from module import * makes it unclear where functions come from. It can also overwrite existing variables in your script silently (e.g., if both your script and the module have a variable named x).

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.