lnNoam
lnNoam

Reputation: 1055

Get all objects of a given structure, and their global names

Suppose I have the following objects:

gray       =    (132, 132, 132)
green      =    (0, 104, 0)
red        =    (168, 0, 68)

How can I obtain all such globals() of this form (RGB) and the name of the corresponding objects?

Upvotes: 1

Views: 44

Answers (2)

nbro
nbro

Reputation: 15878

What about the following shortcut?

ls = [(key, value) for key, value in globals().items() if isinstance(value, tuple) and len(value) == 3]

which creates a list of tuples containing your colors.

Edit:

The previous solution would match also tuples of the form

("hello", "blah", 7)

That is, tuples whose elements could also not be ints.

To prevent this, use the following solution which only accepts tuples whose elements are all ints.

ls = [(key, value) for key, value in globals().items() if isinstance(value, tuple) and len(value) == 3 and all(isinstance(e, int) for e in value) ]

This is similar to what falsetru is doing but just in a compacted way.

Upvotes: 2

falsetru
falsetru

Reputation: 369424

Using isinstance, you can check the type of the objects. And using vars, you will get mapping of variable names to values.

gray = (132, 132, 132)
green = (0, 104, 0)
red = (168, 0, 68)
somethingelse = 0

for key, value in vars().items():
    is_rgb = (
        isinstance(value, tuple) and
        len(value) == 3 and
        all(isinstance(x, int) for x in value)
    )
    if is_rgb:
        print(key)

Another way: try-except

gray = (132, 132, 132)
green = (0, 104, 0)
red = (168, 0, 68)
somethingelse = 0

for key, value in vars().items():
    try:
        _, _, _ = value
        if isinstance(value, tuple):
            print(key)
    except (TypeError, ValueError):
        pass

Upvotes: 3

Related Questions