mercredi 6 mai 2020

Reference with dictionary instead of multiple if, elif, else statements

this is my code:

if dynamic_file_num == "1510":
    self.target = self.config.collection.collection1
elif dynamic_file_num == "0512":
    self.target = self.config.collection.collection2
elif dynamic_file_num == "0511":
    self.target = self.config.collection.collection3
else:
    self.target = self.config.collection.collection4

I extract the first 4 letters of a string and based on that I will set a target value for a database.This code works but I in the production setup I might write 100+ elif statements.

That is why I had the idea to use a dictionary to do this:

reference = {"1512": self.config.collection.collection1,
             "0512": self.config.collection.collection2,
             "0511": self.config.collection.collection3}

self.target = reference.get("1512")

This results of course in an error:

NameError: name 'self' is not defined

Is there a way to write this code without using a ton of if and elif statements?

Aucun commentaire:

Enregistrer un commentaire