如何判断我是否从模块内重新加载()的 Python 模块 [英] How to tell if a Python modules I being reload()ed from within the module

查看:103
本文介绍了如何判断我是否从模块内重新加载()的 Python 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 Python 模块时,有没有办法判断模块是否正在导入或重新加载?

When writing a Python module, is there a way to tell if the module is being imported or reloaded?

我知道我可以创建一个类,并且 __init__() 只会在第一次导入时调用,但我不打算创建一个类.不过,如果没有一种简单的方法可以判断我们是被导入还是重新加载,我会这样做.

I know I can create a class, and the __init__() will only be called on the first import, but I hadn't planning on creating a class. Though, I will if there isn't an easy way to tell if we are being imported or reloaded.

推荐答案

文档reload() 实际上给出了一个代码片段,我认为应该适合您的目的,至少在通常情况下是这样.你会做这样的事情:

The documentation for reload() actually gives a code snippet that I think should work for your purposes, at least in the usual case. You'd do something like this:

try:
    reloading
except NameError:
    reloading = False # means the module is being imported
else:
    reloading = True # means the module is being reloaded

这真正做的是检测模块是干净地"导入(例如第一次)还是覆盖了同一模块的前一个实例.在正常情况下,干净"的导入对应于 import 语句,而脏"的导入对应于 reload(),因为 import> 只真正导入模块一次,第一次执行时(对于每个给定的模块).

What this really does is detect whether the module is being imported "cleanly" (e.g. for the first time) or is overwriting a previous instance of the same module. In the normal case, a "clean" import corresponds to the import statement, and a "dirty" import corresponds to reload(), because import only really imports the module once, the first time it's executed (for each given module).

如果您以某种方式设法强制随后执行 import 语句以做一些重要的事情,或者您以某种方式设法使用 reload() 首次导入模块,或者如果你搞砸了导入机制(通过 imp 模块或类似的东西),所有的赌注都会被取消.换句话说,不要指望这总是在所有可能的情况下都有效.

If you somehow manage to force a subsequent execution of the import statement into doing something nontrivial, or if you somehow manage to import your module for the first time using reload(), or if you mess around with the importing mechanism (through the imp module or the like), all bets are off. In other words, don't count on this always working in every possible situation.

附言你问这个问题的事实让我怀疑你是否在做一些你可能不应该做的事情,但我不会问.

P.S. The fact that you're asking this question makes me wonder if you're doing something you probably shouldn't be doing, but I won't ask.

这篇关于如何判断我是否从模块内重新加载()的 Python 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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