How to pass multiple arguments into function
I'm trying to parse a json file, Suppose the function that is called takes in the json path from a variable called
def traverseJson(arg1): #do stuff section1 = json["section"]["section"]
To call the function I'd run:
How would I then pass in multiple arguments into the function? e.g
section2 = json["section"]["subsection"] section3 = json["section"]["subsection"]
A solution which does not predefine the number of arguments will be more suitable as the number of arguments can vary.
You can pass this kind of arguments as an array or as a dictionary (keyword map).
To pass as an array use
*operator, to pass as a hash, use
def function(first_arg, *args, **kwargs): # something
You can use
def traverse(*args): for arg in args: # logic
section1 = ... section2 = ... traverse(section1, section2) # or sections = [..., ...] traverse(*sections)
If you know the maximum number of args an un-pythonic way of doing it would be
def traverseJson(arg1=0, arg2=0, arg3=0, arg4=0):
If four arguments aren't given it just assigns 0 to the remaining variables.
However, I would recommend passing the arguments as a list. e.g.
def traverseJson(arg1) : for i in arg1: #do stuff traverseJson([section1, section2, section3])
Hope this helps