Search code examples
python-3.xfunctionkeyword-argument

Define a function with dynamic arguments, keyword arguments from user and print them


Code:

def myFun(*args, **kwargs):
    print("args: ", args)
    print("kwargs: ", kwargs)
args = input("Enter args: ")
kwargs = input("Enter kwargs: ")
myFun(args,kwargs)

Output:

Enter args: 1,2,3,4
Enter kwargs: a=5,b=6,c=7
args:  ('1,2,3,4', 'a=5,b=6,c=7')
kwargs:  {}

Process finished with exit code 0

Here the expected output is:

args: (1,2,3,4)

kwargs: {'a':5,'b':6,'c':7}

I am getting the output not as the expected output.


Solution

  • You can use list and dictionary comprehension to parse the input of the users to be list to args and dictionary to kwargs and then unpacked them into myFun.

    def myFun(*args, **kwargs):
        print("args: ", args)
        print("kwargs: ", kwargs)
    
    args = [int(i) if i.isdigit() else i for i in input("Enter args: ").split(",")]
    kwargs = {i.strip().split("=")[0]: int(i.strip().split("=")[1]) if i.strip().split("=")[1].isdigit() else i.strip().split("=")[1] for i in input("Enter kwargs: ").split(",")}
    
    myFun(*args, **kwargs)
    

    Entered

    Enter args: 1,2,3,4
    Enter kwargs: a=5,b=6,c=7
    

    Output

    args:  (1, 2, 3, 4)
    kwargs:  {'a': 5, 'b': 6, 'c': 7}