Search code examples
pythonsyntaxidentifier

Is it possible to programmatically define identifiers using string data in Python?


Suppose I have a class called Circuit, and a dictionary containing data about each circuit component:

components = {
    'V1': [ ... ], 
    'L1': [ ... ], 
    'R1': [ ... ], 
    'R2': [ ... ], 
    ...
}

I want to define child objects Circuit.V1, Circuit.L1, and so on.

The crux of the problem is that I have strings ("V1", "L1", ...) that need to be converted into identifiers. The necessary identifiers would be different depending on what data is passed to the constructor of Circuit, so I can't just hard-code them.

Is this possible, and if so, how do I do this?

I haven't been able to find any information on this (searching just brings up basic info on valid identifier names and such). I have found this page but the question was never directly answered.

Right now I can access my circuit component object like Circuit.components['V1'], but that seems a little clunky and I would prefer Circuit.V1.

Edit: The term for the thing I was trying to do is dynamic attribute assignment. Adding this so that others like me who didn't know what keywords to search for can more easily find information.


Solution

  • Although not recommended, you can use the __setattr__ dunder method:

    class C:
        ...
    
    c = C()
    
    c.__setattr__("V1", 1)
    
    print("c.V1 = ", c.V1) # c.V1 = 1
    
    

    In principle this works, but if you want to define attributes in runtime (you do not know the name of the attributes beforehand) why would you like to treat them as attributes? I think your dictionary approach is better suited for your use case.