Detailed Explanation of python Method for Realizing Variable Variable Names

  • 2021-07-06 11:24:07
  • OfStack

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

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

The easiest thing to think of is eval, but in fact, this dangerous thing is not needed at all, because the variable name of Python is just key of a dictionary. To get this dictionary, use locals and globals functions directly.

Therefore, this program can be implemented as follows:

The code is as follows:


>>> names = locals()

>>> for i in xrange(1, 101):

...  names['x%s' % i] = i

...

>>> x1

1

>>> x2

2

>>> x100

100

However, you may say that this example is useless, after all, it is more practical to use arrays.

Then consider another example: The server uses an object database, which can directly save objects to the database. The server lists all the classes currently supported, and the user wants to add a class that does not exist in the list, so he sends a segment of JSON or XML text to the server. The server parses this text, converts it into an class object, and sets the class name. After that, users can generate objects of this class at will.
The key is that this database is related to the class name. You can't use a general Object class to save all the objects, otherwise the query will be confused.
As it happens, some people put forward this requirement on GAE forum, but he can only give up if he can only know Java.

Of course, you can use it for spoofing if you want:

The code is as follows:


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

>>> True

False

Another use is to test whether a variable name already exists. The standard practice is try... except1 NameError anomalies, which can actually be judged directly by in locals () or in globals ().

By the way, I would like to introduce another strange method. I wonder if anyone has written this:

The code is as follows:


>>> import __main__

>>> hasattr(__main__, 'x')

False

>>> setattr(__main__, 'x', 1)

>>> x

1

>>> hasattr(__main__, 'x')

True

Of course, no one recommended you to write like this, and neither will I.

Finally, in addition to dynamically setting variable names, dynamic deletion is also possible, such as del locals () ['x1']. Similarly, delattr is also available.

Extension of knowledge points:

python dynamically get the variable name of a variable

Requirement goal: If you have the dynamic naming list above, when you dynamically get the variable name of a variable, you need the following operations:

Use the native inspect library of python to realize:

Core code:


import inspect
def get_variable_name(variable):
  callers_local_vars = inspect.currentframe().f_back.f_locals.items()
  return [var_name for var_name, var_val in callers_local_vars if var_val is variable]

Test code:


def get_variable_name(variable):
  callers_local_vars = inspect.currentframe().f_back.f_locals.items()
  return [var_name for var_name, var_val in callers_local_vars if var_val is variable]


if __name__ == '__main__':
  prepare_list = locals()
  for i in range(16):
    prepare_list['list_' + str(i)] = []
    prepare_list['list_' + str(i)].append((' I am the first ' + str(i)) + ' A list')
  a = get_variable_name(prepare_list['list_0']).pop()
  b = get_variable_name(prepare_list['list_1']).pop()
  print(a)
  print(b)


Related articles: