Search code examples
pythongetattr

python more generic solution for using getattr


say I have a test file with the following content:

def a():
    print('this is a')

def b(x):
    print(x)

and also a main file:

import test


def try_cmd(cmd, params):
    try:
        getattr(functions, cmd)(params)
    except Exception as error:
        print(error)


while True:
    cmd = input('Enter cmd')
    params = input('Enter params')
    do_command(cmd, params)

The purpose of the code should be to try to call a function from a different file, with the user giving the function name and if needed params for it to take. What happens is if the value of cmd is 'a' and parmas is a random string do_command will not work because function a doesn't take params. However if cmd will be 'b' and params will be say '5' it will work. How do I get around that without forcing a to take params and not actually using it.


Solution

  • As in my comment on your question, you should write your functions to accept *args and **kwargs, but if you insist on not using this convention, try this:

    def try_cmd(cmd, params):
        func = getattr(functions, cmd)
        try:
            func(params)
        except TypeError:
            func()
        except Exception as error:
            print(error)
    

    In my opinion, accepting *args and **kwargs is the better practice compared to using exception handling to manage branching.