Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid if else to instantiate a class - python

I want to create an object of a class based on value of a field.

For eg:

if r_type == 'abc':
                return Abc()
            elif r_type == 'def':
                return Def()
            elif r_type == 'ghi':
                return Ghi()
            elif r_type == 'jkl':
                return Jkl()

What is a pythonic way to avoid if else here. I was thinking to create a dictionary with r_type being key and classname being value, and do a get of the value and instantiate, is it a proper way, or there is something better idiomatic way in python?

like image 725
inquisitive Avatar asked Aug 01 '18 07:08

inquisitive


2 Answers

You can take advantage of the fact that classes are first class objects in python, and use a dictionary to access the classes you want to create:

classes = {'abc': Abc,    # note: you store the object here
           'def': Def,    #       do not add the calling parenthesis
           'ghi': Ghi,
           'jkl': Jkl}

then create the class like this:

new_class = classes[r_type]()  # note: add parenthesis to call the object retreived

If your classes require parameters, you can place them like in normal class creation:

new_class = classes[r_type](*args, *kwargs)
like image 50
Reblochon Masque Avatar answered Nov 02 '22 07:11

Reblochon Masque


Or dict.get(..) (thanks for the edit Eran Moshe):

classes = {'abc': Abc,
           'def': Def,
           'ghi': Ghi,
           'jkl': Jkl}


new_class = classes.get(r_type, lambda: 'Invalid input')()
like image 3
U12-Forward Avatar answered Nov 02 '22 08:11

U12-Forward