In Python development, as the project size increases, the code is usually scattered in multiple folders. To keep the code modular and maintainable, we often need to introduce Python files from one folder to another. This article will introduce in detail how to introduce .py files in other folders in Python and explore several common implementation methods.
1. Add paths dynamically
When Python imports modules, it will search in the order of paths in it. By default, it contains the directory where the current script is located, the Python installation path, and the path specified by some environment variables. If we need to introduce .py files in other folders, it can be achieved through dynamic modification.
Sample code
Suppose we have the following directory structure:
project/
│
├──
└── utils/
└──
We want to introduce functions in utils/.
# import sys import os # Dynamically add the path to the utils folder(((__file__), 'utils')) import helper helper.say_hello()
# utils/ def say_hello(): print("Hello from helper!")
explain
(): Add the path to the utils folder to enable Python to find it when importing modules.
() and (file): used to dynamically obtain the directory where the current script is located and splice out the path to the utils folder.
Things to note
This approach, while simple, can lead to confusion in large projects and is not conducive to maintenance.
If the path is added improperly, it may cause module conflicts or import errors.
2. Use relative import (for package structure)
If your project is a package (i.e. a folder containing the __init__.py file), you can use relative import to import modules in other folders.
Sample code
Suppose we have the following directory structure:
project/
│
├──
└── utils/
├── __init__.py
└──
We want to introduce functions in utils/.
# from import say_hello say_hello()
# utils/ def say_hello(): print("Hello from helper!")
explain
from import says_hello: import the say_hello function through the package name and module name.
: The existence of this file makes the utils folder treat as a Python package.
Things to note
Relative imports can only be used within the package, and it is necessary to ensure that the package structure is clear.
If the project structure is complex, relative imports may cause confusing import paths.
3. Use PYTHONPATH environment variables
PYTHONPATH is an environment variable that specifies the additional path Python searches for when importing modules. By setting PYTHONPATH, we can introduce modules in other folders without modifying the code.
Sample code
Suppose we have the following directory structure:
project/
│
├──
└── utils/
└──
We want to introduce functions in utils/.
Setting PYTHONPATH in Linux/MacOS
export PYTHONPATH=$PYTHONPATH:/path/to/project/utils
Setting PYTHONPATH in Windows
set PYTHONPATH=%PYTHONPATH%;C:\path\to\project\utils
Import modules in
# import helper helper.say_hello()
explain
PYTHONPATH: By setting this environment variable, Python will search for the specified path when importing the module.
This method does not require modification of the code and is suitable for sharing modules in multiple projects.
Things to note
You need to make sure that the PYTHONPATH is set correctly, otherwise it may cause the import to fail.
In teamwork, it may be necessary to unify the settings of environment variables.
4. Dynamically import modules using importlib
importlib is a module in the Python standard library that provides the function of dynamically importing modules. With importlib, we can dynamically load modules in other folders at runtime.
Sample code
Suppose we have the following directory structure:
project/
│
├──
└── utils/
└──
We want to introduce functions in utils/.
# import import sys import os # The path obtainedmodule_path = ((__file__), 'utils', '') # Dynamic loading of modulesspec = .spec_from_file_location("helper", module_path) helper = .module_from_spec(spec) ["helper"] = helper .exec_module(helper) helper.say_hello()
# utils/ def say_hello(): print("Hello from helper!")
explain
.spec_from_file_location(): Create a module specification based on the file path.
.module_from_spec(): Create a module object according to the module specification.
.exec_module(): Execute the module code and load it into memory.
Things to note
This method is suitable for scenarios where modules need to be loaded dynamically, but the code is relatively complex and is not suitable for regular use.
Dynamic imports may lead to a decrease in readability and maintainability of the code.
5. Use pkgutil and pkg_resources (for package resources)
If your project is a package and needs to load the resource files in the package, you can use pkgutil or pkg_resources to load the module dynamically.
Sample code
Suppose we have the following directory structure:
project/
│
├──
└── utils/
├── __init__.py
└──
We want to introduce functions in utils/.
# import pkgutil import importlib # Dynamically load the helper module in the utils packagehelper = importlib.import_module('') helper.say_hello()
# utils/ def say_hello(): print("Hello from helper!")
explain
importlib.import_module(): Dynamically import the specified module.
pkgutil: provides access to package resources.
Things to note
This method is suitable for dynamic loading of modules in packages, but it needs to ensure that the package structure is clear.
In large projects, dynamic loading can cause performance issues.
Summarize
There are many ways to introduce .py files in other folders in Python, and each method has its applicable scenarios and precautions. For small projects, dynamically adding paths is the easiest way; for projects with package structures, relatively import and PYTHONPATH are better choices; for scenarios where modules are required to be loaded dynamically, importlib and pkgutil provide flexible solutions.
Choosing the appropriate method according to the actual needs of the project can effectively improve the maintainability and readability of the code.
This is the article about this article about teaching you to introduce .py files in other folders in Python. For more related contents of Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!