Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Python auto concatenate strings across lines

Tags:

python

I was creating a long list of strings like this:

tlds = [
  'com',
  'net',
  'org'
  'edu',
  'gov',
...
]

I missed a comma after 'org'. Python automatically concatenated it with the string in the next line, into 'orgedu'. This became a bug very hard to identify.

There are already many ways to define multi-line strings, some very explicit. So I wonder is there a way to disable this particular behavior?

like image 696
Crend King Avatar asked Oct 12 '21 03:10

Crend King


1 Answers

The right Platonic thing to do is to modify the linter. But I think life is too short to do so, in addition to the fact that if the next coder does not know about your modified linter, his/her life would be a living hell.

There should not be shame in ensuring that the input, even if hardcoded, is valid. If it was for me, I would implement a manual workaround like so:

tlds = [
  'com',
  'net',
  'org'
  'edu',
  'gov',
]

redone = ''.join(tlds)
chunk_size = 3
tlds = [ redone[i:i+chunk_size] for i in range(0, len(redone), chunk_size) ]

# Now you have a nice `tlds`
print(tlds)

You can forget commas, write two elements on the same line, or even in the same string all you want. You can invite unwary code collabs to mess it too, the text will be redone in threes (chunk_size) later on anyways if that is OK with your application.

EDIT: Later to @Jasmijn 's note, I think there is an alternative approach if we have a dynamic size of entries we can use the literal input like this:

tlds = ['''com
net
org
edu
gov
nl
co.uk''']

# This way every line is an entry by its own as seen directly without any quotations or decorations except for the first and last inputs.
tlds = '\n'.split(tlds)
like image 184
Bilal Qandeel Avatar answered Nov 20 '22 08:11

Bilal Qandeel