Use list name as string

Tim Chase python.list at tim.thechases.com
Wed Feb 4 18:46:13 CET 2009


> can I do it the otherway, that issavedata('nameoflist')

for limited cases where your variable is defined globally, you 
can use:

   >>> a = [1,2,3,4]
   >>> def save(s):
   ...     print globals().get(s, "UNDEFINED")
   ...
   >>> save("a")
   [1, 2, 3, 4]
   >>> save("b")
   UNDEFINED
   >>> b = (6,5,4,3)
   >>> save("b")
   (6, 5, 4, 3)

However, it's a hideous hack, and fragile as demonstrated by

   >>> x = 7000
   >>> def baz():
   ...     x = (7,8,9) # this isn't in save()'s globals()
   ...     save("x")
   ...
   >>> baz()
   7000
   >>> x = 8000
   >>> baz()
   8000

and using locals() doesn't help either:

   print locals().get(s, globals().get(s, "UNDEFINED"))

and has even weirder (but totally understandable) behavior:

   >>> save("s")  # "s" hasn't been defined in globals()
   's'

Just pass the filename as a string, and skip trying to sniff 
internal variable-names.  Or you'll experience a world of headaches.

-tkc







More information about the Python-list mailing list