我正在尝试为一种编程语言(苍鹭)设计包和模块系统,它既可以编译也可以解释,而且从我所看到的情况来看,我非常喜欢Python方法。Python拥有丰富的模块选择,这似乎在很大程度上促成了它的成功。
我不知道的是,如果一个模块包含在两个不同的编译包中,那么Python中会发生什么情况:数据是否有单独的副本,或者是共享的?
与此相关的是一堆附带问题:
发布于 2009-12-21 16:35:11
你问了很多问题。以下是一些进一步发展的提示:
发布于 2009-12-21 17:32:07
模块是Python中唯一真正的全局对象,所有其他全局数据都基于模块系统(它使用sys.modules作为注册表)。包只是用于导入子模块的具有特殊语义的模块。“将”.py文件编译为.pyc或.pyo并不像大多数语言所理解的那样:它只检查语法并创建代码对象,当在解释器中执行时,该代码对象将创建模块对象。
example.py:
print "Creating %s module." % __name__
def show_def(f):
print "Creating function %s.%s." % (__name__, f.__name__)
return f
@show_def
def a():
print "called: %s.a" % __name__互动会议:
>>> import example
# first sys.modules['example'] is checked
# since it doesn't exist, example.py is found and "compiled" to example.pyc
# (since example.pyc doesn't exist, same would happen if it was outdated, etc.)
Creating example module. # module code is executed
Creating function example.a. # def statement executed
>>> example.a()
called: example.a
>>> import example
# sys.modules['example'] found, local variable example assigned to that object
# no 'Creating ..' output
>>> d = {"__name__": "fake"}
>>> exec open("example.py") in d
# the first import in this session is very similar to this
# in that it creates a module object (which has a __dict__), initializes a few
# variables in it (__builtins__, __name__, and others---packages' __init__
# modules have their own as well---look at some_module.__dict__.keys() or
# dir(some_module))
# and executes the code from example.py in this dict (or the code object stored
# in example.pyc, etc.)
Creating fake module. # module code is executed
Creating function fake.a. # def statement executed
>>> d.keys()
['__builtins__', '__name__', 'a', 'show_def']
>>> d['a']()
called: fake.a你的问题:
is操作符和id() )之外,复制应该与共享没有区别。
mungepath/__init__..py:
print __path__
__path__.append(".") # CWD, would be different in non-example code
print __path__
from . import example # this is example.py from above, and is NOT in mungepath/
# note that this is a degenerate case, in that we now have two names for the
# 'same' module: example and mungepath.example, but they're really different
# modules with different functions (use 'is' or 'id()' to verify)互动会议:
>>> import example
Creating example module.
Creating function example.a.
>>> example.__dict__.keys()
['a', '__builtins__', '__file__', 'show_def', '__package__',
'__name__', '__doc__']
>>> import mungepath
['mungepath']
['mungepath', '.']
Creating mungepath.example module.
Creating function mungepath.example.a.
>>> mungepath.example.a()
called: mungepath.example.a
>>> example is mungepath.example
False
>>> example.a is mungepath.example.a
False发布于 2009-12-21 16:08:18
全局数据的作用域在解释器级别。
https://stackoverflow.com/questions/1940934
复制相似问题