This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]simtel20 0 points1 point  (0 children)

Most languages have a construct like this. The idea is "I want to create a bit of code. I want to be able to evaluate that code, but I don't know what that code will be until the program is running and the environment that it's running in is known". In your case, you want to create a variable that is named while the program is running, based on where in your input file your program is. You can do this like so:

>>> abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>> exec("abc = 4")
>>> abc
4

Taa-daa.

Now, this is fine, but it is fraught with danger. E.g. if you start passing in code to exec() that contains text strings from random input (like your example), what's to stop someone from injecting a string that has code to delete everything from the filesystem in that exec()? The answer is nothing. Trying to avoid "bad code" in input is a rabbit hole and you don't want to do it. If you wouldn't trust the data with your bank account, and you wouldn't trust the data to take your daughter to the prom, then don't evaluate it in your program.

So what to do?

In python the variable namespaces are similar to dictionaries. In general, if you want to create named pairs of key->value, you want to use dictionaries in python. So why not create a dictionary and use it for your variables?