从模块中检测`import module` vs` from module import *` [英] Detecting `import module` vs `from module import *` from module

查看:167
本文介绍了从模块中检测`import module` vs` from module import *`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止模块内部的某些名称被模块import * 语句中的导入,以减少名称空间混乱。 (让我知道这是不好的设计。)

I want to prevent certain names inside a module from being imported by the from module import * statement to reduce namespace cluttering. (Let me know if this is bad design.)

这是我想要的行为(使用 os posix 作为示例):

Here's the behavior I want (using os and posix as an example):


  • import os 应该使 os.posix 可用。

  • 来自os import * 不应该使 posix 可用。

  • 我不在乎是否从os import posix 导致错误。

  • import os should make os.posix available.
  • from os import * should not make posix available.
  • I don't care whether from os import posix results in an error.

导入模块中的代码是否可能模块检测是否从模块导入中导入导入模块导入*

Is it possible for code in an imported module module to detect whether it was imported with import module or from module import *?

推荐答案


导入的模块模块中的代码是否可以检测它是使用导入模块导入还是从模块导入*?

Is it possible for code in an imported module module to detect whether it was imported with import module or from module import *?

是的,至少在CPython中。但这不是一件非常有用的事情,它肯定无法解决你想要解决的问题。 答案当然是使用 __ all __ ,正如mgilson所示。

Yes, at least in CPython. But it's not a very useful thing to do, and it's certainly not going to solve the problem you wanted to solve. The right answer is, of course, to use __all__, as mgilson shows.

但是让我们说明为什么这是错误的答案。

But let's show why this is the wrong answer.

首先,这是一种方法:

import sys
import opcode

f1 = sys._getframe(1)
op = f1.f_code[f1.f_lasti+3]
del f1
if op == opcode.opmap['IMPORT_FROM']:
    print('from me import something')
elif op == opcode.opmap['IMPORT_STAR']:
    print('from me import *')
elif op == opcode.opmap['STORE_NAME']:
    print('import me')

所以,既然你掌握了这些信息,你能用它做什么?在 IMPORT_STAR 案例中不导入 posix ?你的模块在没有它的情况下仍然可以正常工作吗?

So, now that you have that information, what can you do with it? Not import posix in the IMPORT_STAR case? Is your module still going to work without it?

最重要的是,请记住模块可以经常多次导入。如果一个模块用 import foo 导入你,而另一个模块从foo import * 导入,你想要发生什么? ?而且,即使你有答案,你怎么可能这样做,因为你的模块代码只是第一次运行?它必须看到未来检测到其他人将从foo import * 稍后

On top of that, remember that modules can be—and frequently are—imported multiple times. If one module imports you with import foo, and another later does from foo import *, what do you want to happen? And, even if you have an answer, how could you possibly do that, given that your module code only gets run the first time? It would have to see into the future to detect that someone else is going to later from foo import *.

这篇关于从模块中检测`import module` vs` from module import *`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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