Creating Variable Names for Variables in Python

OK, you’ve not just entered the matrix. Googling Google is dangerous some say, but what about variable variable names in Python. As in variables where both neither the value (as expected) or the name stay the same.

Variables are simple little buckets for us to store data and they’re a core part of any program beyond the most basic.

Python is no exception, variable names are a crucial aspect of this ever increasingly popular programming language as they provide a way to store and manipulate data.

Any developer will tell you that it is common practice, and essential for your sanity, to use meaningful and descriptive names for variables but there may be some more complex situations where you want to create variable names dynamically at runtime (P.S. this WILL make debugging a nightmare!).

Reading on isn’t for the feint hearted but if you do want to create variable names dynamically at runtime (or ‘variable’ variable names) in Python then this is the post for you!

In essence, variable variable names are not known until runtime – hence the debugging nightmare. However, you may find it to be the solution if you are working with large dynamic datasets – such as from a database – and you want to create variables on-the-fly and this cannot be determined before runtime.

Let’s run through a few ways we could do this.

Using locals()

locals() is a function that returns all the local variables that are in the current scope – essentially all the variables that you function can currently ‘see’. You can use locals() to dynamically create your variables and assign a name to them based on a string value (the name).

Let’s take a look at some code:

for i in range(5):
    locals()['var_' + str(i)] = i * 2

print(var_0) # Output: 0
print(var_1) # Output: 2
print(var_2) # Output: 4
print(var_3) # Output: 6
print(var_4) # Output: 8

In the example above, we create five variables with names ‘var_0’ to ‘var_4’ inclusive and assign them values using the loop. Easy peasy!

Using setattr()

Another way is to use the setattr() function. It’s used to set the value of a named attribute of an object. And after all, you can just think of your variables as an array or object in your program. This function can be used in a very similar way/concept as to the above – assigning a variable name based upon the value of a string.

Here’s some code to help you visualise it:

class MyClass:
    pass

for i in range(5):
    setattr(MyClass, 'var_' + str(i), i * 2)

print(MyClass.var_0) # Output: 0
print(MyClass.var_1) # Output: 2
print(MyClass.var_2) # Output: 4
print(MyClass.var_3) # Output: 6
print(MyClass.var_4) # Output: 8

Using a dictionary

This one is like an array of arrays – containing the names of the variables which themselves subsequently contain the values. Apologies for the cognitive overload at this stage, but lets look at an example to help out:

my_dict = {}
for i in range(5):
    my_dict['var_' + str(i)] = i * 2

print(my_dict['var_0']) # Output: 0
print(my_dict['var_1']) # Output: 2
print(my_dict['var_2']) # Output: 4
print(my_dict['var_3']) # Output: 6
print(my_dict['var_4']) # Output: 8

Pretty similar to the other ways don’t you think? Anyways, there’s three slightly different ways of doing the same thing. Same effect and very similar processes and probably ultimately comes down to which one you find easier to understand and maintain in your own codebase!

Final Thoughts…

Remember the phrase “just because you can, doesn’t mean you should”? Well that’s never been more applicable than in the case of variable variables names – whether it’s in Python or other programming languages.

Sure they can feel like a godsend but they are also a nightmare to maintain! Make sure you use these sparingly, with care, and knowing what you’re getting into! Dynamic variable names WILL make your code harder to maintain, WILL make it harder for others to understand and WILL probably cause you to have several mini-breakdowns whilst trying to debug an error – as anyone who has previously used them will attest to!

Make sure you’ve studied your use case well and thought about the alternatives before going down this path.

No developer ever said ‘I wish I’d used more variable variable names’ on their deathbed…

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x