How to protect yourself from missing a comma in a vertical string list in python?

In python, it usually has vertically oriented lists of strings. For instance:

subprocess.check_output( [ 'application', '-first-flag', '-second-flag', '-some-additional-flag' ] ) 

It looks good, readable, does not break the rule of 80 columns ... But if the comma is omitted, like this:

 subprocess.check_output( [ 'application', '-first-flag' # missed comma here '-second-flag', '-some-additional-flag' ] ) 

Python will still consider this code valid by combining two bites :( Is there any way to protect myself from such typos while maintaining vertically oriented string lists and without bloating the code (for example, wrapping each element inside str() )?

+6
source share
3 answers

You can wrap each line in parens:

 subprocess.check_output( [ ('application'), ('-first-flag'), ('-second-flag'), ('-some-additional-flag'), ] ) 

And btw, Python is in order with a trailing comma, so always use a comma at the end of the line, which should also reduce errors.

+3
source

You may have commas at the end of the line after spaces, for example:

 subprocess.check_output( [ 'application' , '-first-flag' , '-second-flag' , '-some-additional-flag' , ] ) 

The implementation of this method looks a little worse, but it is easy to notice if you missed any arguments.

+4
source

perhaps for this particular case:

 arglist = 'application -first-flag -second-flag -some-additional-flag' arglist = arglist.split() subprocess.check_output(arglist) 

Or, if you find yourself writing a lot of unique lists like this, create a macro that concatenates the lines into a list form, so you avoid entering a comma manually.

+3
source

Source: https://habr.com/ru/post/926565/


All Articles