A few days ago, M from our Python Cat Communication learning group asked a question. This is an interesting problem, and after our first discussion, we decided that it had no solution.
However, I thought it was valuable enough to continue thinking about how to solve it, so I documented it on the private planet of Knowledge.
Unexpectedly, on the second day, two students came up with solutions one after another!
As a result, there was a round of enthusiastic technical exchange within the group.
This article will be related to the main points of the comb, and from this extended to further learning topics, I hope to help you.
1. How to generate variable names dynamically?
M’s questions are as follows:
Excuse me everybody, ask A question, the known list = [‘ A ‘, ‘B’, ‘C’, ‘D’], how can we get new list named element in A list that A = [], B = [], C = [], D = []?
Simply put, this problem means that the string contents are used as variable names for other objects.
The elements in the list are strings, where ‘A’ – ‘D’ are constants, and a-d are variables in the desired result.
If you force a constant directly as a variable, it will report an error:
>>> 'A' = []
...SyntaxError: can't assign to literal
Copy the code
Literal in an error refers to a literal, which is a common concept in computer science and is used to express fixed values in source code. For example, primitive types such as integers, floating point numbers, and strings are literals.
A literal is a quantity itself, which can be understood as an atomic entity that can no longer be assigned a value.
Therefore, the contents of the string can not be used as a variable name directly, so we need to find another way.
List [0] = [] Of course not, because there’s no A. A = list[0], and then A = []? And that doesn’t work either, because the A here is something you’ve defined out of thin air, not something you’ve generated from something you already know.
At that time, only two or three students in the group participated in the discussion, and we didn’t think of a solution. However, I think this topic is very interesting, worth pondering.
Because, if you can solve this problem, it means that you can dynamically generate variable names without having to define them in advance, which not only reduces the hassle of naming variables, but also achieves automatic coding!
Imagine the future, when artificial intelligence is writing code, if it can dynamically generate variable names according to known conditions, the process of writing code will be much smoother, right? (It is said that there is now an artificial intelligence can write code, I wonder it in the variable name, is using what method?)
There is always a way
Recently, a couple of advertisers were slipped into the study group, so I decided to raise the bar, for example, by asking questions from the group.
To my surprise, Q, the first student to be assessed, came up with a solution to the above problems almost without thinking. But it happened that at almost the same time, student J in the group gave another solution (he didn’t know this problem until he saw the records of knowledge Planet instead of the discussion in the group).
That is to say, the problem that was thought to be unsolvable one night was solved in two different ways the next day!
So what’s their answer?
# J
>>> list1 = ['A'.'B'.'C'.'D'] > > >for i in list1:
>>> globals()[i] = []
>>> A
[]
Copy the code
This method subtly “defines” new variables by modifying the global namespace. The globals() method returns A dictionary in which the string ‘A’ is A key that is A variable in the global namespace, thus converting from A constant to A variable.
At the data structure level, the empty list [] is bound to its string key as a value, and at the application level, it is bound to its variable name as variable content.
When I saw this answer, I suddenly remembered that last month I posted a post about the pitfalls of dynamic assignment in Python. I seem to be focusing on the difference between the use of globals() and locals() without really grasping their original uses.
J said that he had learned this method just by reading the article. This is interesting. I shared a knowledge that I swallowed without understanding, and then it was absorbed and mastered by J. Finally, it was fed back to solve my problem.
I really feel the charm of knowledge sharing: knowledge gains life in the flow and shines in the collision.
At the same time, I really understand the benefits of a mutual learning group: benefit others also benefit themselves, mutual help and progress together.
3. Methods of dynamically executing code
Q, a new student in the group, provided a different answer:
Answer by # Q
>>> list1 = ['A'.'B'.'C'.'D'] > > >for i in list1:
>>> exec(f"{i} = []")
>>> A
[]
Copy the code
His method uses the F-strings feature introduced in Python 3.6. In fact, it can be implemented in earlier versions of Python by ensuring that the exec() method takes a string containing the variable I, for example:
The following code replaces line 4 of the above example
exec(i + = "[]")
# or:
exec("{} = []".format(i))
# or:
exec(' '.join([i, = '[]']))
Copy the code
The differences are only string concatenation. See 7 Ways to Concatenate Strings in Python for more information on how to concatenate strings and the differences between different methods.
Q: The core of this answer lies in the exec() method, which is built in to execute code segments stored in strings or files.
Its basic usage is as follows:
>>> exec('x = 1 + 2')
>>> x
3
# Execute code snippet
>>> s = """
>>> x = 10
>>> y = 20
>>> sum = x + y
>>> print(sum)
>>> """
>>> exec(s)
30
Copy the code
Exec () = exec() = exec() The I extracted from the for-loop is a string, and the concatenated string is processed by exec() to achieve the effect of writing code dynamically.
That is, because the contents of the string constant are executed as valid code, the ‘A’-‘D’ element takes on A new identity, becoming the final a-d variable name.
This method seems very simple, but because the exec() method is so unfamiliar, we didn’t realize it until Q proposed it.
Note: in Python3, exec() is a built-in method; In Python2, the exec() method is a statement and an execfile() method is combined to form the exec() method in Python3. Python3 is used in this article.
4, summarize
Abstracting from the original question, it actually asked “how to use string contents as variable names for other objects” and, more specifically, “how to convert constants to variables”.
Using the static method of direct assignment does not work.
The methods proposed by the two students are indirect dynamic methods: one is to dynamically assign variables and implant variables by modifying the namespace; One is to execute code dynamically, so to speak, by inserting variables through the back door.
Both methods led to the same result, and both cats caught mice, whether they were white or black.
These two methods have brought us valuable enlightenment, and because of them, the group partners are more divergent to discuss some related topics, such as: S proposed another way to modify the writing of variables in namespaces. L mentioned the meaning of eval() and the difference between eval() and exec(). I found out why eval() should be used cautiously
Although some topics cannot be fully developed in a group chat, the extended connection of knowledge on these topics greatly enriched the question at the beginning of this paper. This small question involves two large knowledge systems.
Finally, I really want to thank the excellent comrades who love learning in the group! In addition to what is mentioned in the article, some students also made positive contributions, everyone is very helpful!
Related links:
The Pitfalls of Dynamic Assignment in Python
7 Ways to concatenate Strings in Python
The eval (), exec () and its related functions: www.tuicool.com/wx/vEbeumE
Python Cat is dedicated to Python technology, data science and deep learning. It aims to create an interesting and useful platform for learning and sharing. This series of high-quality articles, including cat philosophy cat series, Python advanced series, good books recommended series, quality English recommendation and translation, welcome to pay attention to oh. PS: backstage reply “love learning”, get a free learning gift package.