5
5
----------
6
6
问题
7
7
----------
8
- You want to reload an already loaded module because you’ve made changes to its source.
8
+ 你想重新加载已经加载的模块,因为你对其源码进行了修改。
9
9
10
10
|
11
11
12
12
----------
13
13
解决方案
14
14
----------
15
- To reload a previously loaded module, use imp .reload(). For example:
15
+ 使用imp .reload()来重新加载先前加载的模块。举个例子:
16
16
17
17
.. code-block :: python
18
18
@@ -27,19 +27,13 @@ To reload a previously loaded module, use imp.reload(). For example:
27
27
----------
28
28
讨论
29
29
----------
30
- Reloading a module is something that is often useful during debugging and development,
31
- but which is generally never safe in production code due to the fact that it doesn’t
32
- always work as you expect.
30
+ 重新加载模块在开发和调试过程中常常很有用。但在生产环境中的代码使用会不安全,因为它并不总是像您期望的那样工作。
33
31
34
32
35
- Under the covers, the reload() operation wipes out the contents of a module’s underlying
36
- dictionary and refreshes it by re-executing the module’s source code. The identity
37
- of the module object itself remains unchanged. Thus, this operation updates the module
38
- everywhere that it has been imported in a program.
33
+ reload()擦除了模块底层字典的内容,并通过重新执行模块的源代码来刷新它。模块对象本身的身份保持不变。因此,该操作在程序中所有已经被导入了的地方更新了模块。
39
34
40
35
41
- However, reload() does not update definitions that have been imported using statements
42
- such as from module import name. To illustrate, consider the following code:
36
+ 尽管如此,reload()没有更新像"from module import name"这样使用import语句导入的定义。举个例子:
43
37
44
38
.. code-block :: python
45
39
@@ -50,7 +44,7 @@ such as from module import name. To illustrate, consider the following code:
50
44
def grok ():
51
45
print (' grok' )
52
46
53
- Now start an interactive session:
47
+ 现在启动交互式会话:
54
48
55
49
.. code-block :: python
56
50
@@ -62,15 +56,15 @@ Now start an interactive session:
62
56
grok
63
57
>> >
64
58
65
- Without quitting Python, go edit the source code to spam.py so that the function grok()
66
- looks like this:
59
+ 不退出Python修改spam.py的源码,将grok()函数改成这样:
60
+
67
61
68
62
.. code-block :: python
69
63
70
64
def grok ():
71
65
print (' New grok' )
72
66
73
- Now go back to the interactive session, perform a reload, and try this experiment:
67
+ 现在回到交互式会话,重新加载模块,尝试下这个实验:
74
68
75
69
.. code-block :: python
76
70
@@ -85,12 +79,7 @@ Now go back to the interactive session, perform a reload, and try this experimen
85
79
New grok
86
80
>> >
87
81
88
- In this example, you’ll observe that there are two versions of the grok() function loaded.
89
- Generally, this is not what you want, and is just the sort of thing that eventually leads
90
- to massive headaches.
91
-
82
+ 在这个例子中,你看到有2个版本的grok()函数被加载。通常来说,这不是你想要的,而是令人头疼的事。
92
83
93
- For this reason, reloading of modules is probably something to be avoided in production
94
- code. Save it for debugging or for interactive sessions where you’re experimenting with
95
- the interpreter and trying things out.
96
84
85
+ 因此,在生产环境中可能需要避免重新加载模块。在交互环境下调试,解释程序并试图弄懂它。
0 commit comments