The Story:
When a list of strings is defined on multiple lines, it is often easy to forget a comma between list items, like in this example case:
test = [
"item1"
"item2"
]
The list test
would now have a single item "item1item2"
.
Quite often the problem appears after rearranging the items in a list.
Sample Stack Overflow questions having this issue:
The Question:
Is there a way to, preferably using static code analysis, issue a warning in cases like this in order to spot the problem as early as possible?
This regular expression will find occurrences of the problem. Just 'search all' files in your project.
Tested in https://regex101.com/ and NotePad++
I implemented code based on @Jim's post. May it works in all situations:
The result is:
In real life I would prefer to avoid doing such mistakes; there are good IDE's like Sublime Text which allow you to edit and format lists with multi cursor. If you get used to those concepts these sort of "separation" errors won't happen in your code.
Of course if one has a Team of Developers one could integrate such a tool into the testing environment.
These are merely probable solutions since I'm not really apt with static-analysis.
With
tokenize
:I recently fiddled around with tokenizing python code and I believe it has all the information needed to perform these kind of checks when sufficient logic is added. For your given list, the tokens generated with
python -m tokenize list1.py
are as follows:This of course is the 'problematic' case where the contents are going to get concatenated. In the case where a
,
is present, the output slightly changes to reflect this (I added the tokens only for the list body):Now we have the additional
OP ','
token signifying the presence of a second element seperated by comma.Given this information, we could use the really handy method
generate_tokens
in thetokenize
module. Methodtokenize.generate_tokens()
,tokenize.tokenize()
inPy3
, has a single argumentreadline
, a method on file-like objects which essentially returns the next line for that file like object (relevant answer). It returns a named tuple with 5 elements in total with information about the token type, the token string along with line number and position in the line.Using this information, one could theoretically loop through a file and when an
OP ','
is absent inside a list initialization (whose beginning is detected by checking that the tokensNAME
,OP '='
andOP '['
exist on the same line number) one can issue a warning on the lines on which it was detected.The good thing about this approach is that it is pretty straight-forward to generalize. To fit all cases where string literal concatenation takes place (namely, inside the 'grouping' operators
(), {}, []
) you check that the token is oftype = 51
(or 53 for Python 3) or that a value in any of(, [, {
exists on the same line (these are coarse, top of the head suggestions atm).Now, I'm not really sure how other people go about with these sort of problems but it seems like it could be something you can look into. All the information necessary is offered by
tokenize
, the logic to detect it is the only thing missing.Implementation Note: These values (for example, for
type
) do differ between versions and are subject to change so it is something one should be aware of. One could possibly leverage this by only working with constants for the tokens, though.With
parser
andast
:Another probable solution which is probably more tedious could involve the
parser
andast
modules. The concatenation of strings is actually performed during the creation of the Abstract Syntax Tree so you could alternatively detect it over there.I don't really want to dump the full output of the methods for
parser
andast
that I'm going to mention, but, just to make sure we're on the same page, I'm going to be using the following list initialization statement:In order to get the parse tree generated, use
p = parser.suite(l_init)
. After this is done, you can get a view of it withp.tolist()
(output is too large to add it). What you notice is that there will be three entries for the three differentstr
objectsitem1
,item2
,item3
.On the other hand, when the AST is created with
node = ast.parse(l_init)
and viewed withast.dump(node)
there are only two entries: one for the concatenatedstr
sitem1item2
and one for the other entryitem3
.So, this is another probable way to do it but, as I previously mentioned, it is way more tedious. I'm not sure if line information is available and you deal with two different modules. Just have it as a back thought if you maybe want to play around with internal objects higher in the compiler chain.
Closing Comments: As a closing note, the
tokenize
approach seems to be most logical one in this case. On the contrary though, it seems thatpylint
actually works withastroid
a python lib that eases analysis of Abstract Syntax Trees for python code. So, one should ideally look at it and how it is used inside pylint.Note: Of course, I might be completely over-analyzing it and a simpler 'check for white-space or newline' solution as you guys suggested would suffice. :-)