Reputation: 110382
I have a bunch of variables, and I need to get the name of the variable being set for validation. For example:
studio = 'Warner Brothers'
movie = ''
validation = [studio, movie]
validation_errors = []
for item in validation:
if not item:
validation_errors.append(name of variable)
In the above case, I'd want the result to be:
validation_errors = ['movie']
Is there a simple way to do this without building a dict?
Upvotes: 0
Views: 739
Reputation: 69170
Does it count if Python builds the dict for you?
studio = 'Warner Brothers'
movie = ''
validation = ['studio', 'movie']
validation_errors = []
for item in validation:
if not locals()[item]:
validation_errors.append(item)
However, just building the dict yourself is the better idea.
studio = 'Warner Brothers'
movie = ''
validation = dict(studio=studio, movie=movie)
validation_errors = []
for var, value in validation.items():
if not value:
validation_errors.append(var)
And if you want to make a function out of it:
def validate(**vars):
errors = []
for var, value in vars.items():
if not value:
errors.append(var)
return errors
-->studio = 'Warner Brothers'
-->movie = ''
-->print validate(studio=studio, movie=movie)
['movie']
Upvotes: 0
Reputation: 11544
As an example of how NOT to do it (or maybe as a demonstration of why not to do it), try this code:
def nameof(thing):
i = id(thing)
names = [n for n in globals().keys() if id(globals()[n]) == i]
for name in names:
if name[0] != '_':
return name, names
return names[0], names
It sort of works, though only if the thing you pass it is a global, or has something in the the globals that looks like it. It will also return all sorts of odd matches due to string interning and such.
Upvotes: 0
Reputation: 177715
Don’t hurt yourself. Use a dictionary. Simple is better than complex.
validation = {'studio': studio, 'movie': movie}
validation_errors = []
for key in validation:
if not validation[key]:
validation_errors.append(key)
If you find yourself wanting to use the local namespace like a dictionary, 99% of the time you just want a dictionary.
Upvotes: 6