1

I'm writing some printouts for the debug mode of a script. Is there a compact way to print the names of those variables in a list that meet a condition?

specification_aw3 = 43534
specification_hg7 = 75445
specification_rt5 = 0
specification_nj8 = 5778
specification_lo4 = 34
specification_ee2 = 8785
specification_ma2 = 67
specification_pw1 = 1234
specification_mu6 = 0
specification_xu8 = 12465

specifications = [
    specification_aw3,
    specification_hg7,
    specification_rt5,
    specification_nj8,
    specification_lo4,
    specification_ee2,
    specification_ma2,
    specification_pw1,
    specification_mu6,
    specification_xu8
]

if any(specification == 0 for specification in specifications):
    # magic code to print variables' names
    # e.g. "variables equal to 0: \"specification_rt5\", \"specification_mu6\"

Just as 9000 suggests, it goes without saying that defining a dictionary is a rational approach for the minimal working example I have defined here. Please assume that this is not a feasible option for the existing code project and that I am looking for a quick, compact (plausibly ugly) bit of code to be used solely for debugging.


EDIT: illustration of something similar to what I want

So here's the beginnings of what I'm looking for:

print("specifications equal to zero:")
callers_local_objects = inspect.currentframe().f_back.f_locals.items()
for specification in [specification for specification in specifications if specification == 0]:
    print([object_name for object_name, object_instance in callers_local_objects if object_instance is specification][0])

Basically, is there a compact way to do something like this?

Community
  • 1
  • 1
d3pd
  • 7,935
  • 24
  • 76
  • 127

2 Answers2

12

I suggest that instead of a bunch of variables you use a dict:

specification = {
  'aw3': 0,
  'foo': 1,
  'bar': 1.23,
  # etc
} 

You can access things by name like specification['aw3'].

Then you can find out names for which the value is 0:

zeroed = [name for (name, value) in specification.items() if value == 0]
9000
  • 39,899
  • 9
  • 66
  • 104
1

In addition, since you mentioned printing the line would be:

for element in specification_dictionary:
  print(element)

where you can combine it with a list comprehension as above for printing only the elements that meet your case. Element in this case only prints the variable name (key) if you want both the key and value just set it to use specification_dictionary.items(). Cheers.

>>> specification = { 'aw3': 0, 'foo': 1}
>>> for element in specification:
...     print(element)
... 
foo
aw3
>>> for (key, value) in specification.items():
...     print(str(key) + " " + str(value))
... 
foo 1
aw3 0
>>> for element in specification.items():
...     print(element)
... 
('foo', 1)
('aw3', 0)
DocBot
  • 21
  • 2