Methods that use dynamic variable names in Python

  • 2020-04-02 13:39:02
  • OfStack

If you were to write a program where x1 is 1, x2 is 2, and then x100 is 100, what would you do?

In a static language like C, the variable name identifier is actually translated by the compiler directly into the memory address, so there is no way to do this except manually setting the value of each variable. A dynamic language like Python can do that.

The easiest thing to think of is eval, but you don't really need this dangerous thing because Python variable names are just keys to a dictionary. To get the dictionary, simply use the locals and globals functions.

So this program can be implemented like this:


>>> names = locals()
>>> for i in xrange(1, 101):
...   names['x%s' % i] = i
...
>>> x1
1
>>> x2
2
>>> x100
100

But you might say that this example isn't useful, because it's more practical to use arrays.

Consider another example: the server USES an object database that can save objects directly to the database. The server lists all the currently supported classes, and the user wants to add a class that does not exist in the list, so he sends a JSON or XML text to the server. The server parses the text, converts it to a class object, and sets the class name. The user is then free to generate objects for this class.
The point is that the database is related to the class name, and you can't use a generic Object class to hold all the objects, otherwise the query will be messy.
As it happens, the request was also made on the GAE forum, and the java-only user finally gave up.

Of course, you can use it as a spoof:


>>> locals()['True'] = False
>>> True
False

Another use is to test whether a variable name already exists. The standard practice is to try... Except for a NameError exception, you can actually just say in locals() or in globals().
And by the way, there's another weird way, and I don't know if anyone has written this:


>>> import __main__
>>> hasattr(__main__, 'x')
False
>>> setattr(__main__, 'x', 1)
>>> x
1
>>> hasattr(__main__, 'x')
True

Of course, no one has recommended it, and neither will I.

Finally, in addition to setting the variable name dynamically, it is also possible to delete dynamically, such as del locals()['x1']. Delattr is also available.


Related articles: