Wildcards for Python Variables

A terrible experimental feature

Can you use wildcards in variable names? Yes. Should you? No. Should we ever consider wildcards for variables? Probably not. Should we try it once and write a post about it? Of course!!

I’ve wished this feature many times when writing code. A sample use case would be when you’re writing a quick print statement to test things out and you just want to print all variables that start with a prefix.

Here’s my implementation of supporting wildcards for variable names in Python, which is a terrible, terrible idea (for various code readability and bug-prone reasons), but fun nevertheless.

import sys 
import fnmatch
def V(wildcard):
variables = sys._getframe(1).f_locals
rets = []
for var in variables.keys():
if fnmatch.fnmatch(var, wildcard):
return rets

Here’s an example of what it would enable:

coord_x = 1 
coord_y = 2
coord_z = 3
print V("coord*")

Note: This would also work if called from a function.

Apart from being a dangerous feature to have in a programming language, this is also not a perfect implementation. The order in which the variables are fetched is random because “variables” is a dictionary.

Despite all the bad things you can say about this, I think it would be a neat feature to have in an editor. It would be similar to some of the features of emmet used by web developers. Imagine typing coord*, hitting tab and getting all three variables in the line (comma separated).