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
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.
Why not simply declare your constants in a dictionary?
Easy looping and easy key retrieval.
Blegh. Item retrieval is awfully ugly compared to attribute retrieval.
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.
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)
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.
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
}
Probably want to use startswith('cs_') instead in case there are other matches