0

i'm trying to do this:

I have the class Caller

    class Caller:
       add = lambda a, b : a + b
       concat = lambda a, b : f'{a},{b}'
       divide = lambda a, b : a / b
       multiply = lambda a, b : a * b

and the function fn()

    def fn(fn_to_call, *args):
    
       result = None

       if fn_to_call == 'add':
           result = Caller.add(*args)
       if fn_to_call == 'concat':
           result = Caller.concat(*args)
       if fn_to_call == 'divide':
           result = Caller.divide(*args)
       if fn_to_call == 'multiply':
           result = Caller.multiply(*args)

       return result

and what i would like to do, is to reduce the fn code to only one line. First, i have the thought of using a one-line if, some like

    return Caller.add(*args) if fn_to_call is 'add' else Caller.concat(*args) if fn_to_call is 'concat' else Caller.divide(*args) if fn_to_call is 'divide' else Caller.multiply(*args) if fn_to_call is 'multiply' else None;

but , i think that was going to be a bad practice. I realized that the name of the lambda attribute of the class Caller it will be equal to the param fn_to_call (add, concat, divide, multiply) So, i wanted to know if it was possible to call an attribute of the function dynamically. Something like:

def fn(fn_to_call, *args):
   return Caller."some_magic_method"(fn_to_call, *args) 
guidoenr4
  • 11
  • 1

1 Answers1

0

You can use the class's __dict__ property:

def fn(fn_to_call, *args):
    return Caller.__dict__[fn_to_call](*args)

or the getattr function:

def fn(fn_to_call, *args):
    return getattr(Caller,fn_to_call)(*args)
Alain T.
  • 40,517
  • 4
  • 31
  • 51