Browse the list of variables initialized on a Project Library

Hello, is it possible to make a for loop to browse the list of variables initialized on a Project Library file, see the example below ?

I want do something like:
for each items in A_Constante ....
I want read each value of constant declared

Try dir(VMS.A_Constante)

Then, in your loop, use getattr(VMS.A_Constante, someNameVar)

Note that it will show every name in the module, including system-defined names.

3 Likes

Why not simply declare your constants in a dictionary?
Easy looping and easy key retrieval.

3 Likes

Blegh. Item retrieval is awfully ugly compared to attribute retrieval.

1 Like

Yea but if he's going through the whole list he wouldn't be using ['someKey'] notation but hopefully rather for key, value in myConstants.items(): # Do stuff. I don't know I use constant dictionaries a decent amount, I'll concede it's slightly ugly but the ability to subnest dictionaries when needed is nice.

1 Like

Thank you for your answer.
I had created a list. I put in the list of each constant and, it worked but on our project we are recommended to use the notation as in the attached image above. but I don't know it is the best solution.

You could use a simple class to achieve a 'namespace', and then some Python sugar to make it directly iterable as well:

class Constants(object):
    CONSTANT_1 = 1
    CONSTANT_2 = "hello"
    CONSTANT_3 = 3.14

    @classmethod
    def __iter__(cls):
        return (getattr(cls, attr) for attr in dir(cls) if attr.isupper())
for constant in Constants:
    print(constant)
2 Likes

And then you risk lifetime problems if you use one of those constants in a persistent place. dir() and getattr() are perfectly reasonable ways to access constants.

I try it but I obtained many thinks that I don't understand where it cam from
image

What @pturmel is suggesting is something more like this:

return [
     getattr(VMS.A_Constante,attr)
     for attr in dir(VMS.A_Constante)
     if 'cs_' in attr
]

This would return a list of all attributes that contain 'cs_' in the name.

You could also do this:

return {
        attr:getattr(VMS.A_Constante,attr)
        for attr in dir(VMS.A_Constante)
        if 'cs_' in attr
        }
1 Like

Probably want to use startswith('cs_') instead in case there are other matches

4 Likes