Prasad, Ramit wrote:
Steven D'Aprano wrote:
Robert Sjoblom wrote:
On 30 April 2012 23:25, Comer Duncan <comer.dun...@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.
--
Steven
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor