Python 的 module 和 package

概要

Python 的 module 和 package。

博客

博客地址:IT老兵驿站

前言

学 Python 也有一段时间了,一直没有搞清楚 module 和 package 的区别和概念,走了一些弯路,所以需要做做笔记,总结一下。

本文结合着对于这篇文章的阅读,进行记录笔记,不打算全文翻译,那样没有意义,扼要地记录关键的,感觉需要记录的内容。

正文

编写 module 的方式

There are actually three different ways to define a module in Python:

A module can be written in Python itself.
A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module.
A built-in module is intrinsically contained in the interpreter, like the itertools module.

一共3种方式,Python 自己编写,由C 语言编写,动态加载,由解释器内部包含的内建 module。

编写方式

Here, the focus will mostly be on modules that are written in Python. The cool thing about modules written in Python is that they are exceedingly straightforward to build. All you need to do is create a file that contains legitimate Python code and then give the file a name with a .py extension. That’s it! No special syntax or voodoo is necessary.

非常简单,就是编写一个合法的 Python 的代码,以 .py 的扩展名结束,就是这么简单。

module 搜索目录

  • The directory from which the input script was run or the current directory if the interpreter is being run interactively
  • The list of directories contained in the PYTHONPATH environment variable, if it is set. (The format for PYTHONPATH is OS-dependent but should mimic the PATH environment variable.)
  • An installation-dependent list of directories configured at the time Python is installed

引入一个 module,是需要从一些位置去搜索,当前运行目录,PYTHONPATH 变量配置的目录,安装依赖的目录。

The resulting search path is accessible in the Python variable sys.path, which is obtained from a module named sys:

1
2
3
4
5
>>> import sys
>>> sys.path
['', 'C:\\Users\\john\\Documents\\Python\\doc', 'C:\\Python36\\Lib\\idlelib',
'C:\\Python36\\python36.zip', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib',
'C:\\Python36', 'C:\\Python36\\lib\\site-packages']

这些搜索路径会保存在 sys.path 里面,可以通过上面的方式获得。

换一个角度来说,想知道被导入的一个 module 的路径,可以通过以下的方式:

1
2
3
4
5
6
7
>>> import mod
>>> mod.__file__
'C:\\Users\\john\\mod.py'

>>> import re
>>> re.__file__
'C:\\Python36\\lib\\re.py'

总结

这篇文章其实看了有些时候了,当时感觉基本掌握了,直到今天,认真地做了一下笔记,逐字逐句地阅读了一番,感觉又明白了不少东西。

参考

https://realpython.com/python-modules-packages/