0

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.

1

2 Answers 2

1

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} 
Sign up to request clarification or add additional context in comments.

2 Comments

The value in the dictionary should be int not str.
Edited the code to convert numbers to int in the dictionary.
1

So there are a few things here to note, you args are coming out as strings because they are being passed as strings. kwargs and args are variable names, but *args and **kwargs are not. So what you're trying to do is probably something like:

def parseArgs(inputString): return(inputString.split(',')) def parseKWargs(inputString): d = {} for element in parseArgs(inputString): current = element.split('=') d[current[0]] = current[1] return(d) def myFun(*args, **kwargs): print("args: ", args) print("kwargs: ", kwargs) args = parseArgs(input("Enter args: ")) kwargs = parseKWargs(input("Enter kwargs: ")) myFun(*args, **kwargs) 

kwargs needs to be a dictionary and "passed by reference" I believe is the correct way to word that. Hope this helps.

Thanks wjandrea for the good catches

3 Comments

Check the output. This isn't quite correct. I'm getting args: (['1', '2', '3', '4'],) and kwargs: {'a': '5', 'b': '6', 'c': '7'}
BTW, don't use input as a variable name cause it shadows the builtin input(). Also argparse is the name of a standard library module, so you may want to use a different name to avoid confusion, but nbd.
@wjandrea is absolutely correct, using input is a bad practice; only meant for demonstrative purposes, and I will update the example to return multiple arguments instead of an argument list momentarily.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.