0

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.

NUAcKSha
  • 11
  • 2
  • I'm not quite clear on what you are asking. What exactly are you trying to get around? You need to define a useful interface for how you want to input things. You need to define some way to input "nothing" for params... this is totally up to you how you want to accomplish this, and what you expect a user to be able to do. – juanpa.arrivillaga Apr 12 '21 at 22:52
  • The called function should accept `*args` and `**kwargs`, even if it disregards them. https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs – Michael Ruth Apr 12 '21 at 22:54

2 Answers2

0

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.

Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
-1

If you're already importing your "test" file, you can look at locals() and globals(), for example:

getattr(locals()['test'],'a')()
Michel
  • 1