1. The necessity of modular programming
Why split the code into different files?
- Functional decoupling: Each module focuses on a single responsibility
- Code reuse: Avoid repeated wheel creation
- Collaborative development: Multiple people develop different modules in parallel
- Convenient maintenance: Quick positioning problem module
- Namespace: Avoid function/variable name conflicts
Typical project structure example
my_project/ ├── utils/ │ ├── __init__.py │ ├── math_tools.py │ └── string_utils.py ├── core/ │ ├── __init__.py │ └── └──
2. Detailed explanation of basic import methods
1. Create basic modules
createmath_tools.py
:
# utils/math_tools.py def circle_area(radius): return 3.14159 * radius ** 2 def fibonacci(n): # Implement Fibonacci sequences pass
2. Basic import method
Method 1: Import the entire module
# import utils.math_tools print(utils.math_tools.circle_area(5)) # Output78.53975
Method 2: Import specific functions
from utils.math_tools import fibonacci print(fibonacci(10)) # Output55
Method 3: Use an alias
from utils.math_tools import circle_area as ca print(ca(3)) # Output28.27431
3. Advanced import skills
1. Two solutions for cross-directory import
Solution A: Dynamically add system paths
import sys ("/path/to/my_project") # Pay attention to using absolute paths from utils.string_utils import reverse_string
Solution B: Create Python package
- Add in each directory
__init__.py
File (can be empty file) - Import using package structure:
from utils.math_tools import circle_area # Automatically identify the package structure
2. Relative import (applicable to package internals)
existImport the same level module:
# core/ from .data_parser import parse_data # A single point represents the current directory
existImport the upper directory module:
from ..utils import string_utils # Two points represent the upper directory
4. Best practices for enterprise-level projects
1. Recommended import order
- Python Standard Library
- Third-party library
- Local module
import os import sys import numpy as np import pandas as pd from utils.math_tools import calculate
2. Loop import cracking solution
When appearImportError: cannot import name
hour:
- Refactoring the code structure
- Delayed import (import inside the function)
- Merge related modules
3. The wonderful use
createutils/__init__.py
:
# Expose common functionsfrom .math_tools import circle_area from .string_utils import reverse_string __all__ = ['circle_area', 'reverse_string']
5. FAQ Troubleshooting Guide
1. Error: ModuleNotFoundError
- Check if the file path is correct
- confirm
__init__.py
exist - Check whether the project root directory is included
2. Error: ImportError
- Avoid loop import
- Check if there is a spelling error in the imported object
- Confirm that there is no syntax error in the imported module
3. Survey of unexpected behaviors
# View imported modulesprint(()) # Check the function sourceprint(fibonacci.__module__)
6. Performance optimization suggestions
-
Cache mechanism: Python caches imported modules (
)
- Lazy loading mode: Import non-required modules inside the function
-
Precompiled bytecode:use
.pyc
File speedup import - Avoid repeated imports: Python will automatically prevent duplicate loading
Through this article, you have mastered the core skills of Python modular programming. Now you can try to refactor your project, follow the principle of "high cohesion and low coupling" and create a clear module structure.
This is the end of this article about five practical methods for calling functions across files in Python. For more related content on Python cross-file calling functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!