Search code examples
pythonindentationpep8

What is the best Python way to represent next line of code?


The basic idea was to write a line like this:

url = 'https://{host}?key={key}&lang={lang}&text='.format(**data)  + '&text='.join(words)

Wanted to rewrite it with PEP 8 Style, so wrote this:

url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) \
    + '&text='.join(words)

What one of those is right?

If neither, I would like to hear why, and see how would you write it.


Solution

  • The urlencode function can handle this case -- even with your list of words:

    from urllib.parse import urlencode
    
    host = 'example.com'
    data = {'key': 'asdf', 'lang': 'en-us', 'text': ['sam', 'i', 'am']}
    params = urlencode(data, True)
    url2 = 'https://{host}?' + params
    

    This will produce: https://example.com?key=asdf&lang=en-us&text=sam&text=i&text=am

    Note that urlencode is called with doseq parameter set to True to handle your list of repetitive parameters.