在python中,有没有办法从对象本身找到包含变量或其他对象的模块?
举个例子,假设我定义了一个变量,其中可能有多个变量
from __ import *
from ____ import *
等。
有没有办法找出命名空间中的一个变量的定义位置?
编辑
谢谢,但我已经明白 import * 通常被认为是糟糕的形式。但这不是问题,而且无论如何我都没有写它。如果有一种方法可以找到变量的来源,那就太好了。
As an example, say I have a variable defined where there may be multiple
from __ import *
from ____ import *
etc.
Is there a way to figure out where one of the variables in the namespace is defined?
edit
Thanks, but I already understand that import * is often considered poor form. That wasn't the question though, and in any case I didn't write it. It'd just be nice to have a way to find where the variable came from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是为什么在大多数情况下在 python 中使用
from __ import *
被认为是不好的形式。使用from __ import myFunc
或import __ as myLib
。然后,当您需要myLib
中的某些内容时,它不会与其他内容重叠。如需在当前命名空间中查找内容的帮助,请查看 pprint 库,内置目录,内置本地变量、内置全局变量。
This is why it is considered bad form to use
from __ import *
in python in most cases. Either usefrom __ import myFunc
or elseimport __ as myLib
. Then when you need something frommyLib
it doesn't over lap something else.For help finding things in the current namespace, check out the pprint library, the dir builtin, the locals builtin, and the globals builtin.
不,由
from blah import *
定义的名称不会保留有关其来源的任何信息。这些值可能有线索,例如,类具有__module__
属性,但它们可能已在一个模块中定义,然后从另一个模块导入,因此您不能指望它们是您想要的值。预计。No, the names defined by
from blah import *
don't retain any information about where they came from. The values might have a clue, for example, classes have a__module__
attribute, but they may have been defined in one module, then imported from another, so you can't count on them being the values you expect.例如,排序:
Attribute
的模块可能看起来令人惊讶,因为这不是您导入它的位置,但它是Attribute
的位置代码>类型已定义。查看zope/interface/common/idatetype.py
,我们看到:这解释了
__module__
的值。您还会遇到从其他模块导入的类型实例的问题。假设您创建一个名为att
的Attribute
实例:同样,您正在了解类型的来源,而不是变量的定义位置。
不使用通配符导入的最大原因很可能是你不知道你得到的是什么,它们会污染你的命名空间,并可能破坏其他类型/变量。
即使现在
import *
可以无冲突地工作,也不能保证将来更新导入的包时不会发生这种情况。Sort-of, for example:
The module of the
Attribute
may seem surprising since that is not where you imported it from, but it is where theAttribute
type was defined. Looking atzope/interface/common/idatetype.py
, we see:which explains the value of
__module__
. You'll also run into problems with instances of types imported from other modules. Suppose that you create anAttribute
instance namedatt
:Again, you're learning where the type came from, but not where the variable was defined.
Quite possibly the biggest reason to not use wildcard imports is that you don't know what you're getting and they pollute your namespace and possibly clobber other types/variables.
Even if today the
import *
works without collision, there is no guarantee that it won't happen with future updates to the package being imported.如果您在解释器中调用该方法本身,它会告诉您它的父模块是什么。
例如:
If you call the method itself in the interpreter it will tell you what it's parent modules are.
For example: