Initialize class more efficiently in Python

Question:

I have this code in which I initialize a class (Adapter) by the name I get from the request.
It seems to be a bit clumsy, and I’m sure there’s a better/cleaner way of doing it.

from adapters.gofirst_adapter import GoFirstAdapter
from adapters.spicejet_adapter import SpiceJetAdapter
from adapters.airasia_adapter import AirAsiaAdapter

class Adapter():
    def __init__(self, adapter_name):
        if(adapter_name=='goFirst'):
            gofirst_adapter = GoFirstAdapter()
            self.adapter = gofirst_adapter
        if(adapter_name=='spiceJet'):
            spicejet_adapter = SpiceJetAdapter()
            self.adapter = spicejet_adapter
        if(adapter_name=='airAsia'):
            airasia_adapter = AirAsiaAdapter()
            self.adapter = airasia_adapter

What I’m aiming at is to have a list of the adapter names such as:

adapters = ['goFirst', 'spiceJet', 'airAsia']

and create the classes by the list.

Thank you.

Asked By: Daniel Avigdor

||

Answers:

You can use a dict to map the parameter to the specific class:

from adapters.gofirst_adapter import GoFirstAdapter
from adapters.spicejet_adapter import SpiceJetAdapter
from adapters.airasia_adapter import AirAsiaAdapter

class Adapter():
    adapters = {'goFirst':GoFirstAdapter, 'spiceJet':SpiceJetAdapter, 'airAsia':AirAsiaAdapter}
    def __init__(self, adapter_name):
        self.adapter = self.adapters[adapter_name]()
Answered By: quamrana

something like this could work:

from adapters.gofirst_adapter import GoFirstAdapter
from adapters.spicejet_adapter import SpiceJetAdapter
from adapters.airasia_adapter import AirAsiaAdapter

class Adapter():
    _adapter_builders = {
        "goFirst": GoFirstAdapter,
        "spiceJet": SpiceJetAdapter,
        "airAsia": AirAsiaAdapter,
    }

    def __init__(self, adapter_name):
        self.adapter = self._adapter_builders[adapter_name]()

Also it will raise an exception when the key is not available in the dictionary.

Answered By: J. Ferrarons
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.