[Tutor] question about listing variables defined since session started

Prasad, Ramit ramit.prasad at jpmorgan.com
Tue May 1 17:42:13 CEST 2012


Steven D'Aprano wrote:
> Prasad, Ramit wrote:
> >> Steven D'Aprano wrote:
> >> Robert Sjoblom wrote:
> >>> On 30 April 2012 23:25, Comer Duncan <comer.duncan at gmail.com> wrote:
> >>>> Hi,
> >>>>
> >>>> I have a newbie type question.  Say I have started a python (or
> >>>> ipython) session and have done some imports and have also defined
> some
> >>>> new variables since the session started.  So, I have in my current
> >>>> namespace a bunch of things. Suppose I  want to list just those
> >>>> variable  names which have been defined since the session started but
> >>>> not include the names of the objects that who and whos will return.
> >>>> How to do that?
> >>> Not entirely sure, but something like this might work (untested):
> >>> for name in dir():
> >>>     myvalue = eval(name)
> >>>     print name, "is", type(name), "and is equal to ", myvalue
> >> Please do not use eval unless you know what you are doing, and
> certainly
> >> don't
> >> encourage newbies to use it without a word about the risks.
> >>
> >
> > ast.literal_eval(name) is probably safer.
> 
> Safer, but doesn't work:
> 
> 
> py> import ast
> py> name = 25
> py> ast.literal_eval('name')
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "ast.py", line 87, in literal_eval
>      return _convert(node_or_string)
>    File "ast.py", line 86, in _convert
>      raise ValueError('malformed node or string: ' + repr(node))
> ValueError: malformed node or string: <_ast.Name object at 0xb7a9560c>
> 
> 
> literal_eval is for evaluating literals, not names.
> 
> py> ast.literal_eval('[123, "ABC", None, {}]')
> [123, 'ABC', None, {}]
> 
> 
> It apparently can also do simply arithmetic, but that's *possibly* an
> implementation detail due to the keyhole optimizer in CPython's compiler.
>

What about just using dir / globals / locals?

global_variables = globals()
for name in dir():
   value = globals_variables[ name ] if name in global_variables else locals[ name ]
   print '{0} is {1} and is equal to {2}'.format( name, type(value), value )   

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list