Python包不是源自文件系统

在描述导入系统的
python
documentation中,有以下内容(我强调):

[…] You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. […]

在文件系统中分别存储与文件和文件夹不对应的模块和软件包有哪些选项?

read关于从zip档案加载模块和包的可能性.这是引用段落引用的可能选项之一吗?
还有其他这样的选择吗?

最佳答案 这是您可以考虑包和模块的方式,但包/模块不是文件系统中的目录/文件.

您可以将包/模块存储在zip文件中,并使用zipimport加载它.

您可以从字符串变量加载模块:

import imp

code = """
def test():
    print "function inside module!"
    """

# give module a name
name = "mymodule"
mymodule = imp.new_module(name)
exec code in mymodule.__dict__

>>> mymodule.test()
function inside module!
点赞