列出用户定义的变量python

时间:2012-04-24 16:33:34

标签: python variables

我试图遍历python脚本中设置的变量。我发现了以下内容:

Enumerate or list all variables in a program of [your favorite language here]

并在第一个例子中:

#!/us/bin/python                                                                                    

foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

它列出了存储在内存中的所有变量。我想隔离我在脚本中创建的变量,而不是列出默认创建的系统变量。有没有办法做到这一点?

5 个答案:

答案 0 :(得分:8)

默认情况下,您可以检查模块中包含的变量是否位于内置__builtins__模块中,如下所示:

>>> x = 3
>>> set(dir()) - set(dir(__builtins__))
set(['__builtins__', 'x'])

唯一没有消除的是__builtins__本身,这很容易发生特殊情况。

另请注意,如果您重新定义了任何内置名称,则无法使用此功能。你不应该在实践中这样做,但很多人都是这样做的,很多是偶然的。

答案 1 :(得分:7)

如果你没有在你的变量前加上任何下划线,你可以这样做:

#!/us/bin/python                                                                                    

foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"

for name in dir():
    if not name.startswith('__'):
        myvalue = eval(name)
        print name, "is", type(myvalue), "and is equal to ", myvalue

答案 2 :(得分:2)

这是解决方案。

#!/us/bin/python    

not_my_data = set(dir())

foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"

my_data = set(dir()) - not_my_data

for name in my_data :
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

但这是不好的做法。

您应该使用类似

的内容
#!/us/bin/python    
my_data = dict()                                                                                   
my_data['foo1'] = "Hello world"
my_data['foo2'] = "bar"
my_data['foo1'] = {"1":"a", "2":"b"}
my_data['foo1'] = "1+1"

for name in my_data :
    myvalue = eval(my_data[name])
    print name, "is", type(name), "and is equal to ", myvalue

答案 3 :(得分:0)

我想要更多类似matlab'whos'的内容,所以我把它烘焙了: 要点here

import __main__
def whos(lss):
 fil = __main__.__file__
 thisthinghere = open(fil).read().split("\n")
 vs = []
 for l in thisthinghere:
    if l.find("=") > -1:
        vs.append(l.split("=")[0].strip())
 keys = lss.keys()
 out = {}
 for v in vs:
    try: 
        out[v] = lss[v]
    except:
        "not in list"
 keys = out.keys()
 keys.sort()
 for k in keys:
    val = str(out[k])
    if len (val) > 10:
        if val[-1] == ")":val = val[0:10]+"..."+val[-10:]
        elif val[-1] == "]" :val = val[0:10]+"..."+val[-10:]
        else: val = val[0:10]
    print k,":",val

 return out

#import into your script and call with whos(locals())
它似乎有效。它将打印变量空间,并将其作为字典返回,以便于酸洗/ jsoning。

答案 4 :(得分:0)

问题标题使我看到了这一点。但这不是我想要的。

自我回答在下面

NavHost(navController, startDestination = startRoute) {
    ...
  navigate(nestedRoute, startDestination = nestedStartRoute) {
    composable(route) {
        ...
        // This instance will be the same
        val parentViewModel: YourViewModel = it.parentViewModel(navController)
    }
    composable(route) {
       ...
        // As this instance
        val parentViewModel: YourViewModel = it.parentViewModel(navController)
    }
  }
  navigate(secondNestedRoute, startDestination = nestedStartRoute) {
    composable(route) {
        ...
         // But this instance is different
         val parentViewModel: YourViewModel = it.parentViewModel(navController)
    }
  }
  composable(route) {
     ...
     // This is also different (the parent is the root graph)
     // but the root graph has the same scope as the whole NavHost
     // so this isn't particularly helpful
     val parentViewModel: YourViewModel = it.parentViewModel(navController)
  }
  ...
}