<p><strong><em>通过在模块上显式访问模块级变量来显式访问模块级变量</p>
<hr/>
<p>简而言之:</strong>这里描述的技术与<a href="https://stackoverflow.com/a/1978076/2889970">steveha's answer</a>,<strong><em>中描述的技术相同,除了</em></strong>之外,不创建任何人工辅助对象来显式地限定变量的范围。<em>相反,模块对象本身被赋予一个变量指针,因此在从任何地方访问时都提供显式的作用域。(类似于本地函数范围内的赋值)</em>。</p>
<p>把它想象成当前模块而不是当前实例的self</em></strong>!</p>
<pre class="lang-python prettyprint-override"><code># db.py
import sys
# this is a pointer to the module object instance itself.
this = sys.modules[__name__]
# we can explicitly make assignments on it
this.db_name = None
def initialize_db(name):
if (this.db_name is None):
# also in local function scope. no scope specifier like global is needed
this.db_name = name
# also the name remains free for local use
db_name = "Locally scoped db_name variable. Doesn't do anything here."
else:
msg = "Database is already initialized to {0}."
raise RuntimeError(msg.format(this.db_name))
</code></pre>
<p><a href="https://stackoverflow.com/a/2029528/2889970">As modules are cached and therefore import only once</a>,您可以在任意数量的客户机上导入<code>db.py</code>,操作相同的通用状态:</p>
<pre class="lang-python prettyprint-override"><code># client_a.py
import db
db.initialize_db('mongo')
</code></pre>
<pre class="lang-python prettyprint-override"><code># client_b.py
import db
if (db.db_name == 'mongo'):
db.db_name = None # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
</code></pre>
<pre class="lang-python prettyprint-override"><code># client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value
# that "db.db_name" has at import time of "client_c".
if (db_name == 'mongo'): # checking is fine if "db.db_name" doesn't change
db_name = None # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.
</code></pre>
<hr/>
<p>作为一个额外的奖励,我发现它总体上是相当Python的,因为它很好地符合Python的政策,<em>显式优于隐式</em>。</p>