How to make Python interpreter a little more strict?

John Pote johnhpote at o2.co.uk
Sat Mar 26 19:30:30 EDT 2016



On 26/03/2016 12:05, Chris Angelico wrote:
> On Fri, Mar 25, 2016 at 11:06 PM, Aleksander Alekseev <afiskon at devzen.ru> wrote:
>> Recently I spend half an hour looking for a bug in code like this:
>>
>> eax at fujitsu:~/temp$ cat ./t.py
>> #!/usr/bin/env python3
>>
>> for x in range(0,5):
>>      if x % 2 == 0:
>>          next
>>      print(str(x))
>>
>> eax at fujitsu:~/temp$ ./t.py
>> 0
>> 1
>> 2
>> 3
>> 4
>>
>> Is it possible to make python complain in this case? Or maybe solve
>> such an issue somehow else?
> I think what you're looking for here is an acknowledgement that
> evaluating the name "next" accomplishes nothing. That's not really
> something the Python interpreter should be looking at (hey, you might
> have good reason for doing that), but there are linters that can
> detect this kind of dead code. Some of them tie into programmer's
> editors, so you could get a nice little warning message right in the
> window where you're typing your code. Look into some of the top-end
> editors (free or commercial) and see what you think of them - they can
> save you no end of time.
>
> ChrisA
So intrigued by this question I tried the following
def fnc( n ):
     print "fnc called with parameter '%d'" % n
     return n

for i in range(0,5):
     if i%2 == 0:
         fnc
         next
     print i

and got the same result as the OP

D:\projects\python
 >>python next.py
0
1
2
3
4
D:\projects\python
 >>

A couple of tests showed that the only important thing about the name in 
the if clause is that it is known at runtime and then it is silently 
ignored.
However, if the name is not known/accessible at run time a 'NameError' 
is raised,
NameError: name 'mynewfn123' is not defined

On the other hand the following if clause
     if i%2 == 0:
         fnc    next

results in a compiler error,
D:\projects\python
 >>python next.py
   File "next.py", line 9
     fnc next
            ^
SyntaxError: invalid syntax

This is all for Python 2.7.9. (Don't know about Python 3....).

So I have sympathy with the OP, I would expect the compiler to pick this 
up - indeed it does so for two (or more ?) unused names on a single 
line. That is unless someone can give a useful use of this behaviour or 
is there something going on under the Python hood I'm not aware of?

It would be all to easy to write a series of lines just calling 
functions and forget the () on one of them. Not fun programming.
It's also a good reminder that the meaning of a keyword in language A is 
not necessarily the same in language B (ie 'next', Python)
So on this last point is this behaviour of Python defined somewhere in 
the docs?

Regards all,
John




More information about the Python-list mailing list