List of declared variables in interactive Python session?

Raymond Arthur St. Marie II of III rastm2 at aol.commorespam
Sun Jul 20 20:36:06 CEST 2003


>> Hello.
>>
>> Is there a way to list all the declared variables in an interactive
>> Python session?
>
>use "vars() "
>
>HTH,
>
>Vincent Wehren
>
>>
>> Thanks,
>> Fredrik
>>
>
>

I got one for ya. 

I read some where that when the dir( ) has a lot of stuff in it, it is
convenient to use a for loop to see the contents. (example follows) 
Now the reason for my 2 cents in this post. 

>>> 

>>> dir( )

['__builtins__', '__doc__', '__name__', 'pywin']

>>> for d in dir(): print d
... 

__builtins__
__doc__
__name__
pywin

>>> vars( )

{'d': 'pywin', '__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', 'pywin': <module 'pywin' from
'C:\PYTHON22\lib\site-packages\Pythonwin\pywin\__init__.pyc'>, '__doc__': None}

>>> for v in vars(): print v
... 

d   ### prints the first variable I declared in the first for loop then        
   

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
RuntimeError: dictionary changed size during iteration

     ### opps no v in the dir( ) so...
>>> for v in vars(): print v
... 

d
v
__builtins__
__name__
pywin
__doc__

>>>

You can see that you can print the same kind of display for vars( ) as you can
for the dir( ), so long as your iterater variable is declared previous to the
for loop.

Ray St.M
Proudly stating the obvious since birth.




More information about the Python-list mailing list