How do I accomplish variable variables in Python?
Here is an elaborative manual entry, for instance: Variable variables
I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
How do I accomplish variable variables in Python?
Here is an elaborative manual entry, for instance: Variable variables
I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
Any set of variables can also be wrapped up in a class. "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.
The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):
You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.
You can use variable key names to achieve the effect of variable variables without the security risk.
For cases where you're thinking of doing something like
a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:
For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing,
append
, and other operations that would require awkward key management with a dict.Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing
you write
This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".
You have to use
globals()
built in method to achieve that behaviour:The
SimpleNamespace
class could be used to create new attributes withsetattr
, or subclassSimpleNamespace
and create your own function to add new attribute names (variables).I'm am answering the question: How to get the value of a variable given its name in a string? which is closed as a duplicate with a link to this question.
If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are
hasattr
,getattr
, andsetattr
.So for example you can have:
Then you can do: