This code is very self-explanatory, and I just know there has to be a better way. I hope the title is clear enough to understand what I'm trying to do here.
if self.table == 'BodyPart':
working_keys = BodyPart_Keys
elif self.table == 'IncidentEvent':
working_keys = IncidentEvent_Keys
elif self.table == 'InjuryType':
working_keys = InjuryType_Keys
elif self.table == 'ObservationType':
working_keys = ObservationType_Keys
elif self.table == 'TaskStatus':
working_keys = TaskStatus_Keys
elif self.table == 'AuditInspection':
working_keys = AuditInspection_Keys
CodePudding user response:
In this case, I like to use a mapping with a Python dict
object. The main benefit I think is that lookup is 0(1)
so it should be about as efficient as a nested if
condition.
Example:
fn_1 = lambda: 'hi, im function 1'
fn_2 = lambda: 'hello from function 2'
my_mapping = {'A': fn_1,
'B': fn_2}
working_keys = my_mapping[self.table]
print(working_keys())
CodePudding user response:
All you are doing is adding a trailing _Keys
to the table name.
This can be done by simply writing working_keys = self.table '_Keys'
.
If the variables are inside some module you can access the specific variable as module.__dict__[working_keys]
.
If you want an additional check to see whether the table name is only from a selective set of names you can do:
permitted_names = {'BodyPart', 'IncidentEvent', ...} # create a set
if self.table in permitted_name:
do_something()
You need to clarify more details about the variable names, and where they're coming from.