Is it possible to overload from/import in Python?

拥有回忆 提交于 2019-12-30 06:18:27

问题


Is it possible to overload the from/import statement in Python?

For example, assuming jvm_object is an instance of class JVM, is it possible to write this code:

class JVM(object):

  def import_func(self, cls):
    return something...

jvm = JVM()

# would invoke JVM.import_func
from jvm import Foo

回答1:


This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;)




回答2:


It's hard to find something which isn't possible in a dynamic language like Python, but do we really need to abuse everything? Anyway, here it is:

from types import ModuleType
import sys

class JVM(ModuleType):
    Foo = 3

sys.modules['JVM'] = JVM

from JVM import Foo
print Foo

But one pattern I've seen in several libraries/projects is some kind of a _make_module() function, which creates a ModuleType dynamically and initializes everything in it. After that, the current Module is replaced by the new module (using the assignment to sys.modules) and the _make_module() function gets deleted. The advantage of that, is that you can loop over the module and even add objects to the module inside that loop, which is quite useful sometimes (but use it with caution!).



来源:https://stackoverflow.com/questions/3928023/is-it-possible-to-overload-from-import-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!