关于python:重新加载模块提供的功能最初不是通过导入它来获得的。

Reloading a module gives functionality that isn't originally available by importing it. where can i learn more about this?

本问题已经有最佳答案,请猛点这里访问。

这段代码解决了我遇到的一个问题。但是,"setDefaultEncoding"在没有重新加载的情况下不可用。

这种语言的怪癖叫什么?我为什么不早点告诉你?我在哪里能读到更多关于它的信息呢?

1
2
3
import sys;
reload(sys);
sys.setdefaultencoding("utf8")

http://mypy.pythonblogs.com/12_mypy/archive/1253_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html


"怪癖"是指site模块故意删除sys.setdefaultencoding()功能:

1
2
3
4
5
# Remove sys.setdefaultencoding() so that users cannot change the
# encoding after initialization.  The test for presence is needed when
# this module is run as a script, because this code is executed twice.
if hasattr(sys,"setdefaultencoding"):
    del sys.setdefaultencoding

你不应该使用它!将默认编码设置为utf-8就好像断了一根棍子,然后继续走,而不是让医生设置断了的骨头。

真的,让我澄清一下:删除它是有原因的,原因是您将a)破坏任何依赖于正常默认值的模块;b)您正在掩盖实际问题,即通过尽早解码和延迟编码来正确处理Unicode,直到需要再次发送数据为止。

这样一来,reload()函数的工作方式就是让您绕过模块缓存;import将只加载一次python模块;随后的导入将为您提供已经加载的模块。reload()加载模块a-new,就像从未导入过一样,并将新名称合并回现有模块对象(以保留以后添加的额外名称):

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.
  • As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
  • The names in the module namespace are updated to point to any new or changed objects.
  • Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

因此,reload()将删除的sys.setdefaultencoding()名称恢复到模块中。