1

I'm trying to parse a json file, Suppose the function that is called takes in the json path from a variable called section1

def traverseJson(arg1):
    #do stuff

section1 = json["section"]["section"][1]

To call the function I'd run:

traverseJson(section1)

How would I then pass in multiple arguments into the function? e.g

section2 = json["section"]["subsection"][0]
section3 = json["section"]["subsection"][0]

A solution which does not predefine the number of arguments will be more suitable as the number of arguments can vary.

martineau
  • 119,623
  • 25
  • 170
  • 301
Darth
  • 219
  • 2
  • 6
  • 18

3 Answers3

3

You can use *args syntax:

def traverse(*args):
    for arg in args:
        # logic

UPDATE: Usage

section1 = ...
section2 = ...
traverse(section1, section2)

# or

sections = [..., ...]
traverse(*sections) 
Linch
  • 511
  • 4
  • 11
1

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 ** operator.

Example:

def function(first_arg, *args, **kwargs): 
  # something

Read more here and here.

PatNowak
  • 5,721
  • 1
  • 25
  • 31
1

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

dwmyfriend
  • 224
  • 1
  • 10