推理基础设施 · Python4.3 模块与包:把代码拆到多个文件
04
文件操作与简单模块化 · 3 / 4

4.3 模块与包:把代码拆到多个文件

💡 推理框架代码量上万行,不可能写在一个文件里。你必须懂 import

4.3 模块与包

模块 = 一个 .py 文件

# utils.py
def normalize(x):
    return x.strip().lower()

# main.py
import utils
print(utils.normalize("  HI  "))   # hi

几种 import 写法

写法 用法
import utils utils.normalize
from utils import normalize normalize
from utils import normalize as norm norm
import utils as u u.normalize

包 = 包含 init.py 的目录

inference/
├── __init__.py
├── server.py
└── config.py
from inference.server import run

示范

# 文件 prompts.py
SYSTEM_PROMPT = "You are a helpful assistant."

def build_prompt(user_msg):
    return f"{SYSTEM_PROMPT}\nUser: {user_msg}"

# 文件 main.py
from prompts import build_prompt
print(build_prompt("hi"))

✍️ 练习

在当前目录创建两个文件:

  1. sampling.py,里面写:
def apply_temperature(logits, temperature):
    if temperature <= 0:
        return logits
    return [v / temperature for v in logits]
  1. main.py,里面 from sampling import apply_temperature,调用一次 apply_temperature([1.0, 2.0, 3.0], 0.5) 并打印

把代码写到两个文件里运行。

💡 思路提示

点开看提示
  1. from 模块名 import 函数,前提是模块文件在同一个目录或在 sys.path
  2. temperature=0.5 时,logits 除以 0.5 等于乘 2
  3. 如果你嫌麻烦,也可以写在同一个文件里测试 import 逻辑

✅ 参考解法

写不出来再打开
# 文件 sampling.py
def apply_temperature(logits, temperature):
    if temperature <= 0:
        return logits
    return [v / temperature for v in logits]

# 文件 main.py
from sampling import apply_temperature
print(apply_temperature([1.0, 2.0, 3.0], 0.5))   # [2.0, 4.0, 6.0]

🔍 进阶思考

循环引用a.py import b.pyb.py 又 import a.py)会怎样?

  • 答:ImportError
  • 生产代码要避免这种结构,重构时把共用的部分抽到第三个文件 c.py