How to print as a string a callable object?

Viewed 123

I think there should be a question like this already, but I haven't found it. It could be because I don't know the exact concepts/words about what I'm looking for, but here is the example:

I have this code:

group_1 = ['Hello', 'world', '!']
group_2 = [1,23,4,2,5,2]
group_3 = ['A', 'K', 'L']

all_groups = [group_1, group_2, group_3]
for i in all_groups:
    print(i, ':', len(i))

It gives this output:

['Hello', 'world', '!'] : 3
[1, 23, 4, 2, 5, 2] : 6
['A', 'K', 'L'] : 3

And this is the expected output:

'group_1' : 3
'group_2' : 6
'group_3' : 3

As you can see, I'm trying to print the names of the callable objects group_1, group_2, and group_3. Any suggestions?

3 Answers

Restructure your code so that it uses a dictionary to store the group names.

I would not recommend approaches that use anything related to reflection, the inspect module, or locals(), as described (or linked to) in the comments. The names of the variables in all_groups list aren't preserved when you add them to all_groups; even if they were, accessing these names would likely be more complex than just using a dictionary:

data = {
    'group_1': ['Hello', 'world', '!'],
    'group_2': [1,23,4,2,5,2],
    'group_3': ['A', 'K', 'L']
}

for k, v in data.items():
    print(k, ':', len(v))

This outputs:

group_1 : 3
group_2 : 6
group_3 : 3

The following code:

all_groups = [group_1, group_2, group_3]
for i in all_groups:
    print(i, ':', len(i))

Takes the values of those three existing variables group_1, group_2 and group_3 and puts them into a list with three items.

When you iterate over that list and print the items, you get their values, not their names (which is a concept reserved for humans, because we cannot understand code otherwise).

If you want to store their names, you store them in a dictionary:

all_groups = {
  'group_1': group_1,
  'group_2': group_2,
  'group_3': group_3
}

And then print their name using:

for k,v in all_groups.items():
    print(k, ':', len(v))

You can just use globals(), because why not:

group_1 = ['Hello', 'world', '!']
group_2 = [1,23,4,2,5,2]
group_3 = ['A', 'K', 'L']

all_groups = ['group_1', 'group_2', 'group_3']

for grp in all_groups:
    print(locals()['grp'], ':', len(globals()[grp]))
Related