Printing a variable's name not its value

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Jul 20 16:19:06 EDT 2005


travislspencer at gmail.com a écrit :
> Hey,
> 
> I am trying to write a function that takes an arbitrary number of
> arguments and does one of two things.  If the variable is a key in a
> dictionary, it prints the key and its value.  Otherwise, if any of the
> variables isn't in the dictionary, the function prints the variable's
> name and value.
> 
> Here is what I have so far:
> 
> globals = {}

globals() is a builtin function, you should no shadow it.

> HOME_DIR = "The user's home directory"
> SHELL = "The user's shell"
> 
> def someFunction():
>     someString = "This is a test"
>     globals[VERBOSE] = True
>     globals[HOME_DIR] = os.getenv("HOME")
>     globals[SHELL] = os.getenv("SHELL")
> 
>     printVerbose(someString, HOME_DIR, SHELL)

-> printVerbose(HOME_DIR, SHELL, someString=someString)

> def printVerbose(*args):
def printVerbose(*args, **kwargs):

>     if VERBOSE in globals:
>         for a in args:
>             if a in globals:
>                 value = globals[a]

          for k, v in kwargs:
>             print "%s: %s" % (k, v)
> 

(snip)

> I've been told on #python that there isn't a way to get a variable's
> name.  I hope this isn't so.  

It is so. In fact, there is nothing like a 'variable' in Python. What we 
have are names bound to objects. Names 'knows' what objects are bound to 
them, but objects knows *nothing* about names they are bound to.



More information about the Python-list mailing list