已加载模块的导入行为

2024-04-20 08:14:02 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于这种情况:

你知道吗Foo.py公司地址:

import another_module

def foo():
#some code

它是由不同的模块调用的,其中一些模块已经import another_module,而另一些模块则没有主.py')

  1. Which is the default behaviour? Is the module re-loaded?If yes,(that's just a curiosity) let's suppose that another_module has changed between the import in the main and the import in foo.py. Python does have in memory two different version of another_module,one accessible for foo.py and one for main.py?
  2. Is there a way to not import another_module if it has already been done in the main?
  3. How does it works if in the main i have from another_module import f1, and in foo.py from another_module import f1,f2.Is f2 just "added" or module reloaded?

Tags: 模块andtheinpyimportthatfoo
1条回答
网友
1楼 · 发布于 2024-04-20 08:14:02

不,模块没有重新加载。可以使用^{}函数重新加载模块。导入模块后,它将被添加到^{}字典中。如文档所述,还可以通过更改此变量的内容来强制重新加载模块:

This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.

^{}语句对于这种行为没有任何区别。它只控制加载模块的哪些部分被添加到当前作用域:

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The statement comes in two forms differing on whether it uses the from keyword. The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly.

您可以自己轻松验证:

年产量

print "Y"

def f1():
    pass

def f2():
    pass

x.py

print "X"

from y import f1, f2

测试.py

from y import f1

import x

print "reload"

reload(x)

python test.py

Y
X
reload
X

相关问题 更多 >