0

This is my current code:

def flag_a_device_status(context, var):
    if var == '40D':
         context.holder.default_40D = True
    elif var= '212F':
         context.holder.default_212F = True
    elif 
    elif 
    else:... 

As you can see, var is a parameter passing from the upstream code, and its value could be "40D", "200F", "212F", etc. And based on its string value, I need to turn on different flag under context.holder, such as default_40D, default_212F, etc.

Is there a better way to handle that in Python? Something as if:

context.holder.default_"var" = True
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user3595231
  • 711
  • 12
  • 29
  • Why don't you keep the `default_` things in a dictionary? – DYZ Jul 09 '21 at 19:36
  • 2
    Does this answer your question? [How do you programmatically set an attribute?](https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute) – mkrieger1 Jul 09 '21 at 19:39

1 Answers1

1

You can just use exec for your scenario. One more thing, you don't need to have those many if-else statements, for that you can handle it with the below way.

i.e., in your code you're going to add exec(f'context.header.default_{var} = True')

class Context:
  def __init__(self, default_40D = False, default_212F = False):
    self.default_40D = default_40D
    self.default_212F = default_212F

  def test(self):
    print(self.default_40D)
    print(self.default_212F)

variables = ['40D', '212F']
def flag_a_device_status(context, var):
    if var in variables:
         exec(f'context.default_{var} = True')

context = Context()

flag_a_device_status(context, '40D')

context.test()