1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Rep Power

    Naming variables with a variable

    The pseudocode I'd like to do is this:

    varname = raw_input("Enter a string: ")

    var = 5

    Here, though, is what i would like it to do: instead the second variable being called "var", i would like for it to be called by the value of 'varname' (whatever the string is called). Is this even possible?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    London, England
    Rep Power
    It is possible, but not generally advisable, unless you have a really good reason. What if the name that the user entered was the same as a builtin function or variable? If the user entered 'open' and you then tried to open() a file then your program would crash and burn.

    You can create global variables by adding them to the dictionary returned by the globals() function. You cannot do the same for locals() because it returns a copy of the local namespace, not the original. If you really, really must create a local variable the you could do it with an exec:

    >>> name = 'foo'
    >>> exec "%s = 5" % name
    >>> foo
    Exec-ing text that a user has entered is highly dangerous though, and should be avoided at all costs.

    A much better alternative is to either create a dictionary to hold your names in, or create an empty class and use setattr to add members. This way you will not be polluting your program's namespace.
    >>> class Namespace:
    ... 	pass
    >>> namespace = Namespace()
    >>> setattr(namespace, name, 5)
    >>> namespace.foo
    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo