1

Referring to the question above, is there a way to identify how many arguments are passed to a function.

def setup(file1, file2):
    reader1 = PyPDF2.PdfFileReader(file1)
    reader2 = PyPDF2.PdfFileReader(file2)

My goal is to make the function versatile. My plan is to detect how many arguments are passed and then modify the behavior of the function such as, if three files are passed to the function, it will create 3 readers. I'll use for loop to name the readers and pass the right files to the PdfFileReader() function. But, I just do not know how to make the function behave like how I want it to be in the first place.

Sivaprakash B
  • 163
  • 1
  • 15

3 Answers3

2

You can use variable arguments instead:

def setup(*files):
    readers = [PyPDF2.PdfFileReader(file) for file in files]
    return readers

so if, for example, you want call it with 3 files, you can call it with:

reader1, reader2, reader3 = setup(file1, file2, file3)
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

You can make use of *args. Just do like:

def setup(*args):
    reader_list = [PyPDF2.PdfFileReader(el) fro el in args]
Rahul Chawla
  • 1,048
  • 10
  • 15
0

Use the variable number of arguments syntax. For example:

def foo(*args):
   print(len(args))
Yakov Dan
  • 2,157
  • 15
  • 29