蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

模块与包:导入、缓存、路径和命名空间

用本站多文件工程核对导入绑定、包结构及解释器环境。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

模块与缓存的范围

源码文件是模块的一种形式,模块也可来自内置或扩展加载器;sys通常是内置模块,并不存在必须读取的sys.py。模块提供复用、命名空间和组织边界,但可导出的名字仍可能在调用方冲突。

普通import先利用sys.modules缓存,同一解释器中重复导入一般不重跑初始化;importlib.reload会重新执行模块代码,独立解释器也有独立缓存,因此不能把只运行一次理解成永远无法再执行。

模块首次加载会执行顶层语句,包括赋值、函数定义和未受入口条件保护的输出。直接运行 python3-module.py 时,Python 将文件作为程序入口,__name__ 是 __main__,入口条件成立。本站示例运行了 main() 并输出 JSON 检查结果。把同一文件以 module_lesson 名称加载时, __name__ 是 module_lesson,main 仍可调用,导入时标准输出为空。入口条件只控制其代码块, 模块中其余顶层语句仍会执行。

导入形式与两个自编模块

import module绑定模块名,from module import name绑定指定属性而不自动建立同名模块变量;这不意味着模块对象没有实际加载。as只是当前名字的别名,不复制模块或函数。

本站support式模块输出本站欢迎语,另一个模块提供打印/返回列表的斐波纳契函数。分别观察上界100、500、1000及空结果;函数别名、直接import、from和模块__name__各有实例。下载附件原件与本站工程分别登记,不互相冒充。

from module import *受__all__或默认公开名规则影响,不等于复制所有属性。显式__all__可包括下划线名;通常避免星号导入,以免覆盖已有绑定。

搜索路径和解释器差异

搜索过程涉及缓存、元路径查找器及相应加载器,文件系统模块还使用搜索路径。sys.path受启动方式、环境、虚拟环境和site处理影响,不是任何时候都固定为当前目录/PYTHONPATH/标准库/所有.pth的简单顺序。

普通脚本的首项通常是脚本目录,-c或交互式常见空串表示当前目录;隔离模式-I会改变这些条件。本站比较普通与隔离子进程,并只用两个自有目录中的同名测试模块观察优先级,不创建stdlib同名文件。

sys.argv保留实际命令行参数。sys.ps1/ps2属于交互式环境,脚本中不保证存在;本站强制交互子进程观察提示符,未修改用户环境变量、PATH或全局解释器设置。

dir与十个标准库

dir(module)给出可供交互发现的名称,不承诺严格完整的静态API清单;对象可定义__dir__。无参数dir()观察当前局部名字,赋值和del会影响结果;不要把某个旧版本sys列表当所有版本固定输出。

标准库表保留math、os、sys、random、datetime、json、re、collections、itertools、functools的作用,并各运行一个自有小例;functools同时比较reduce和lru_cache,缓存实际命中及底层调用次数分开记录。平台专属模块如winreg要按宿主核对,不把存在于某平台当跨平台保证。

普通包、命名空间包和子模块

常规包使用__init__.py组织初始化,包属性__path__供子模块搜索;Python还支持不带该文件的命名空间包,甚至可由多个目录组成,不能说所有包目录都必须有__init__.py。

本站音频命名空间用formats、effects、filters三个子包说明层级;只做数字序列的简化计算,不冒充真实音频编解码工程。完整路径导入、从包导子模块和直接导函数三个入口都实际使用。

没有__all__的包星号导入不会自动遍历磁盘导入所有子模块;已初始化或已显式导入并绑定的公开名字则可能被导出。设置__all__后按列出的名字处理;这不是解决所有文件名大小写问题的自动机制。

显式相对导入与主模块

点号相对导入依赖包上下文,可指同包或父包,并非一律必须改成绝对导入。python -m package.module可保留正确包上下文;直接执行包内部文件可能缺少上下文而失败。

包内属性、子模块与函数名的查找有不同规则,缺名可以抛ImportError,模块初始化代码也可能抛自己的异常。本站保留正确与失败路径,不把推荐某种导入写法说成永远不会出错。

十个标准模块

模块用途本章实际目标
math数学函数sqrt(9)与sin(0)
os系统与路径自有路径末级名称
sys解释器参数与环境真实argv和内置模块证据
random伪随机生成局部Random可重放
datetime日期和时间ISO日期
jsonJSON序列化自有数据往返
re正则表达式完整匹配
collections额外容器deque出队与defaultdict分组
itertools迭代工具有限取值
functools高阶函数工具reduce归并;lru_cache缓存一次计算并观察命中

导入及包边界

形式绑定限制
import module模块名模块实际加载可执行顶层代码
from module import name指定名称不自动在调用方绑定模块名
as别名对象不因此复制
import *__all__或默认公开名不扫描所有磁盘子模块
普通包__init__.py与__path__初始化/子模块查找
命名空间包可无__init__.py可汇合多个目录
相对导入依赖包上下文-m与直接文件执行有别
reload重新执行模块不等于普通重复import

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com — 自有多文件模块、包及解释器观察。"""
from pathlib import Path
import sys,io,contextlib,subprocess,json,importlib,math,os,random,datetime,re,itertools,functools
from collections import deque,defaultdict
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def main():
    c=Checks()
    import mbsky_support
    out=io.StringIO()
    with contextlib.redirect_stdout(out):result=mbsky_support.print_greeting("学习者")
    c.eq("support real output",out.getvalue(),"蓝色天空网欢迎 学习者\n");c.eq("support returns None",result,None)
    import mbsky_fibonacci as fibo
    c.eq("fibonacci below100",fibo.below(100),[1,1,2,3,5,8,13,21,34,55,89])
    c.eq("fibonacci below500",fibo.below(500),[1,1,2,3,5,8,13,21,34,55,89,144,233,377])
    c.eq("fibonacci below1000 last",fibo.below(1000)[-1],987)
    c.eq("fibonacci empty boundary",fibo.below(1),[])
    out=io.StringIO()
    with contextlib.redirect_stdout(out):fibo.show(10)
    c.eq("module prints fibonacci",out.getvalue(),"1 1 2 3 5 8\n")
    c.eq("module own name",fibo.__name__,"mbsky_fibonacci")
    alias=fibo.below;c.eq("function alias same object",alias is fibo.below,True)
    namespace={};exec("from mbsky_fibonacci import below, show",namespace)
    c.eq("from import only named bindings","below"in namespace and"show"in namespace and"mbsky_fibonacci"not in namespace,True)
    c.eq("module still loaded",sys.modules["mbsky_fibonacci"]is fibo,True)
    namespace={};exec("import mbsky_fibonacci as numbers\nfrom math import sqrt as root",namespace)
    c.eq("module alias object",namespace["numbers"]is fibo,True);c.eq("function alias call",namespace["root"](9),3.0)
    import mbsky_cache_probe
    c.eq("first module initialization",mbsky_cache_probe.LOADS,1)
    second=importlib.import_module("mbsky_cache_probe")
    c.eq("ordinary import uses same object",second is mbsky_cache_probe,True);c.eq("ordinary import does not rerun",second.LOADS,1)
    importlib.reload(second);c.eq("explicit reload reruns",second.LOADS,2)
    c.eq("sys is builtin origin",sys.__spec__.origin,"built-in")
    c.eq("sys has no source filename",hasattr(sys,"__file__"),False)
    c.eq("sys in builtin module names","sys"in sys.builtin_module_names,True)
    argv_runs=[]
    for isolated,flags in [(False,["-E","-s","-B"]),(True,["-I","-B"])]:
        r=subprocess.run([sys.executable,*flags,"-X","utf8",str(P/"mbsky_arg_probe.py"),"参数1","参数2"],capture_output=True,text=True,encoding="utf8",timeout=6)
        c.eq("argv child status "+str(isolated),r.returncode,0);d=json.loads(r.stdout)
        c.eq("actual unicode argv "+str(isolated),d["args"],["参数1","参数2"])
        c.eq("script directory startup rule "+str(isolated),d["scriptdir_first"],not isolated)
        c.eq("actual isolation flag "+str(isolated),d["isolated"],int(isolated));argv_runs.append(d)
    sys.path[:0]=[str(P/"search_b"),str(P/"search_a")]
    import mbsky_search_target
    c.eq("owned path ordering",mbsky_search_target.VALUE,"second owned directory")
    c.eq("noninteractive ps1 not guaranteed",hasattr(sys,"ps1"),False)
    interactive=subprocess.run([sys.executable,"-I","-B","-X","utf8","-i","-c","import sys;sys.ps1='SKY> ';sys.ps2='MORE> '"],input='print("mbsky.com")\nexit()\n',capture_output=True,text=True,encoding="utf8",timeout=6)
    c.eq("interactive child exits",interactive.returncode,0);c.eq("interactive actual stdout",interactive.stdout,"mbsky.com\n")
    c.eq("interactive custom prompt displayed","SKY> "in interactive.stderr,True)
    c.eq("dir includes definitions","below"in dir(fibo)and"__name__"in dir(fibo),True)
    marker=1;c.eq("dir local after assignment","marker"in dir(),True);del marker;c.eq("dir local after delete","marker"in dir(),False)
    class Discover:
        def __dir__(self):return ["custom"]
    c.eq("dir can be customized",dir(Discover()),["custom"])
    c.eq("math sqrt",math.sqrt(9),3.0);c.eq("math trigonometric",math.sin(0),0.0)
    c.eq("os path operation",os.path.basename(str(P/"note.txt")),"note.txt")
    c.eq("random local repeat",random.Random(42).random(),random.Random(42).random())
    c.eq("datetime ISO",datetime.date(2024,2,29).isoformat(),"2024-02-29")
    data={"brand":"蓝色天空网","hours":[1,2]}
    c.eq("json round trip",json.loads(json.dumps(data,ensure_ascii=False)),data)
    c.eq("regex whole match",re.fullmatch(r"mbsky[.]com","mbsky.com")is not None,True)
    q=deque(["HTML","CSS"]);c.eq("collections dequeue",q.popleft(),"HTML")
    grouped=defaultdict(list);grouped["CSS"].append("learn");c.eq("collections default factory",dict(grouped),{"CSS":["learn"]})
    c.eq("itertools finite slice",list(itertools.islice(itertools.count(1),3)),[1,2,3])
    c.eq("functools reduction",functools.reduce(lambda a,b:a*b,[2,3,4]),24)
    computed=[]
    @functools.lru_cache(maxsize=2)
    def square(value):computed.append(value);return value*value
    c.eq("functools cache miss result",square(4),16)
    c.eq("functools cache hit result",square(4),16)
    c.eq("functools cache underlying call",computed,[4])
    c.eq("functools cache hit miss statistics",(square.cache_info().hits,square.cache_info().misses),(1,1))
    import mbsky_audio.effects.echo
    c.eq("full package path call",mbsky_audio.effects.echo.echofilter([1,2]),[1.0,2.5,1.0])
    from mbsky_audio.effects import echo
    c.eq("submodule import same",echo is mbsky_audio.effects.echo,True)
    from mbsky_audio.effects.echo import echofilter
    c.eq("function import same",echofilter is echo.echofilter,True)
    from mbsky_audio.effects import lesson
    c.eq("three relative import forms",lesson.result(),(("wav","aiff","au"),[1.0,2.5,1.0],[2,4]))
    exported={};exec("from mbsky_audio.effects import *",exported)
    c.eq("package all exact names",sorted(k for k in exported if not k.startswith("__")),["echo","reverse","surround"])
    c.eq("all imports reverse module",exported["reverse"].reverse([1,2]),[2,1])
    c.eq("all imports surround module",exported["surround"].stereo([1,2]),[(1,1),(2,2)])
    import mbsky_plain
    c.eq("unlisted submodule not auto loaded","mbsky_plain.hidden_part"in sys.modules,False)
    exported={};exec("from mbsky_plain import *",exported)
    c.eq("without all no filesystem scan",sorted(k for k in exported if not k.startswith("__")),["LABEL"])
    import mbsky_plain.hidden_part
    exported={};exec("from mbsky_plain import *",exported)
    c.eq("already bound public submodule exported","hidden_part"in exported,True)
    exported={};exec("from mbsky_exports import *",exported)
    c.eq("explicit all includes underscore",sorted(k for k in exported if not k.startswith("__")),["_explicit","public"])
    c.eq("explicit all excludes ordinary name","hidden"not in exported,True)
    sys.path[:0]=[str(P/"namespace_a"),str(P/"namespace_b")]
    import mbsky_sharedspace
    from mbsky_sharedspace import left,right
    c.eq("namespace package has no init origin",mbsky_sharedspace.__spec__.origin,None)
    c.eq("namespace package two locations",len(list(mbsky_sharedspace.__path__)),2)
    c.eq("namespace portions both work",(left.VALUE,right.VALUE),("left namespace portion","right namespace portion"))
    c.raises("missing package member ImportError",ImportError,lambda:exec("from mbsky_plain import no_such_member",{}))
    c.finish("python3-module",argv_runs=argv_runs,interactive_prompts_in_owned_child=True,audio_namespace_only_numeric_teaching=True,source_archive_scripts_executed=False)
if __name__=="__main__":main()
运行本章核心实例

所需环境:本地 Python 环境

当前源码 SHA256:086c7651da8dc7edcdc76fd66d1abd7cdf3ad197c5fb27acffb71630dc8ed0ac

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据