Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python switch by class name?

I am currently doing this, to do different things based on an object's type:

    actions = {
        SomeClass: lambda: obj.name
        AnotherClass: lambda: self.normalize(obj.identifier)
        ...[5 more of these]...
    }

    for a in actions.keys():
        if isinstance(obj, a):
            return actions[a]()

Is it possible to cut out the for loop, and do something like this?

actions[something to do with obj]()
like image 228
Lucy Avatar asked Dec 22 '22 05:12

Lucy


1 Answers

class SomeClass( object ):
....
    def action( self ):
        return self.name

class AnotherClass( object ):
....
    def action( self ):
        return self.normalize( self.identifier )

[5 more classes like the above two]

a.action()

Simpler. Clearer. More extensible. Less Magic. No dictionary. No loop.

like image 77
S.Lott Avatar answered Jan 04 '23 00:01

S.Lott