0

I am trying to pass a list of arguments to a function I have created.

def pdftotext(params=[], layout='-layout'):
    cmd = ['pdftotext', params, '-layout']
    return cmd

This is how I call it:

text = pdftotext(params=['-f', '1', '-l', '2'])  
return text              

This generates below:

[
  "pdftotext",
  [
    "-f",
    "1",
    "-l",
    "2"
  ],
  "-",
  "-layout"
]

However, as you can see, an extra [] is added where the params=[] are passed.

I have tried converting the params to a string, like:

params = ','.join(params)

But this doesn't work either, as it simply joins each param and separates it with a comma.

How can I pass a set of different parameters to my function, without it creating a double list?

oliverbj
  • 5,771
  • 27
  • 83
  • 178
  • `cmd = ['pdftotext', params, '-layout']` -> `cmd = ['pdftotext'] + params + ['-layout']` – h4z3 Aug 05 '19 at 10:00

3 Answers3

10

For Python >= 3.5

All you need is to unpack the list of params using *:

>>> params = ['-f', '1', '-l', '2']

>>> ['pdftotext', params, '-layout']
['pdftotext', ['-f', '1', '-l', '2'], '-layout']

>>> ['pdftotext', *params, '-layout']
['pdftotext', '-f', '1', '-l', '2', '-layout']

For earlier versions:

You can use list concatenation:

>>> ['pdftotext'] + params + ['-layout']
['pdftotext', '-f', '1', '-l', '2', '-layout']

It could be better to use a more dynamic approach and change params to be a varargs argument:

def pdftotext(*params, layout='-layout'):
    cmd = ['pdftotext', *params, layout]  # or ['pdftotext'] + params + [layout]
    return cmd

And now you can pass any number of arguments:

>>> print(pdftotext('-f', '1', '-l', '2'))
['pdftotext', '-f', '1', '-l', '2', '-layout']

If you have no control on the input and want to use params as a list you can still do:

>>> print(pdftotext(*['-f', '1', '-l', '2']))
['pdftotext', '-f', '1', '-l', '2', '-layout']
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
4

firstly, be aware of defining the default argument to params as a list: mutable default arguments in python can cause hard-to-find bugs

To solve your primary question, you can use unpacking

cmd = ['pdftotext', *params, '-layout']
Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36
1

you need to concatenate your lists:

cmd = ['pdftotext'] + params + ['-layout']

when you see it in action:

>>> params=['-f', '1', '-l', '2']
>>> cmd = ['pdftotext', params, '-layout']
>>> cmd
['pdftotext', ['-f', '1', '-l', '2'], '-layout']
>>> cmd = ['pdftotext'] + params + ['-layout']
>>> cmd
['pdftotext', '-f', '1', '-l', '2', '-layout']
Chris Maes
  • 35,025
  • 12
  • 111
  • 136