获取当前的 python 模块对象(按名称或其他方式) [英] Get current python module object (by name or otherwise)

查看:104
本文介绍了获取当前的 python 模块对象(按名称或其他方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想获取当前模块,例如要重新加载它,我会这样做:

If I wanted to get the current module, e.g. to reload it, I would do:

import sys
sys.modules[__name__]

有没有更好的方法来做到这一点(例如,不涉及__name__)?在这种情况下,更好意味着更惯用、更便携、更健壮,或者更多......我们通常希望在我们的软件中拥有的任何其他东西.

Is there a better way to do this (e.g. not involving __name__)? Better in this context means more idiomatic, more portable, more robust, or more...any of the other things we usually desire in our software.

我使用 python 2,但 python 3 的答案无疑对其他人有用.

I use python 2, but answers for python 3 will no doubt be useful to others.

推荐答案

没有比你使用的更惯用的方法从 sys.modules 获取当前模块对象.

There is no more idiomatic method to get the current module object from sys.modules than what you used.

__name__ 在导入时由 Python 设置,本质上是:

__name__ is set by Python on import, essentially doing:

module_object = import_py_file(import_name)
module_object.__name__ = import_name
sys.modules[import_name] = module_object

所以 __name__ 引用正是你想在这里使用的.

so the __name__ reference is exactly what you want to use here.

这篇关于获取当前的 python 模块对象(按名称或其他方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆