Python,打印所有绑定变量的名称和值

4
有没有一种方法可以让Python打印出所有绑定变量的名称和值?
(不需要重新设计程序将它们都存储在单个列表中)
4个回答

2

是的,你可以这样做,虽然这种方式有些粗糙,但它对于调试等方面非常有用。

from pprint import pprint

def getCurrentVariableState():
    pprint(locals())
    pprint(globals())

2
这还远远不是所有的绑定变量。 - aaronasterling
@aaron 是的,那只是四个作用域中的两个。内置和非局部作用域还没有提到。 - wjandrea

2

0
dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

0

globals()和locals()分别返回表示全局和局部作用域中符号表的字典。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接