Reci
Reci

Reputation: 4274

Disable Python auto concatenate strings across lines

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?

Upvotes: 13

Views: 640

Answers (2)

Bilal Qandeel
Bilal Qandeel

Reputation: 727

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)

Upvotes: 1

TheEagle
TheEagle

Reputation: 5992

Why don't you simply wrap the strings into str(…) ?. If you forget a comma, a SyntaxError will be raised.

tlds = [
  str('com'),
  str('net'),
  str('org')
  str('edu'),
  str('gov'),
  str('nl'),
  str('co.uk')
]

If all these str's are too much, you can create a temporary alias:

s = str
tlds = [
  s('com'),
  s('net'),
  s('org')
  s('edu'),
  s('gov'),
  s('nl'),
  s('co.uk')
]

(Note: This code intentionally raises a SyntaxError - to eliminate it, the missing comma needs to be added)

Upvotes: 0

Related Questions