読者です 読者をやめる 読者になる 読者になる

vars, locals, globals + Python

スコープに含まれる変数を要素とする辞書を戻す関数メモ。

テストプログラムを書く

  
$ vi vars.py  

  
#!/usr/bin/env python  
# -*- coding: utf8 -*-  
g_name = "tarou"  
g_color = "red"  
  
def func():  
    name = "jirou"  
    color = "blue"  
    print "-"*10, "In function.", "-"*10  
    print "vars ->", vars()  
    print "locals ->", locals()  
    print "globals ->", globals()  
    print "name:%(name)s, color:%(color)s" % vars()  
  
if __name__ == "__main__":  
    func()  
    print "-"*10, "In __main__.", "-"*10  
    print "vars ->", vars()  
    print "locals ->", locals()  
    print "globals ->", globals()  
    print "name:%(g_name)s, color:%(g_color)s" % vars()  

実行してみる

  
$ python vars.py   
---------- In function. ----------  
vars -> {'color': 'blue', 'name': 'jirou'}  
locals -> {'color': 'blue', 'name': 'jirou'}  
globals -> {'__builtins__': , '__file__': 'vars.py', 'func': , 'g_name': 'tarou', '__name__': '__main__', 'g_color': 'red', '__doc__': None}  
name:jirou, color:blue  
---------- In __main__. ----------  
vars -> {'__builtins__': , '__file__': 'vars.py', 'func': , 'g_name': 'tarou', '__name__': '__main__', 'g_color': 'red', '__doc__': None}  
locals -> {'__builtins__': , '__file__': 'vars.py', 'func': , 'g_name': 'tarou', '__name__': '__main__', 'g_color': 'red', '__doc__': None}  
globals -> {'__builtins__': , '__file__': 'vars.py', 'func': , 'g_name': 'tarou', '__name__': '__main__', 'g_color': 'red', '__doc__': None}  
name:tarou, color:red  

雑感

"%(name)s" % (vars()) って記述がわかりやすい。