variable declaration
Peter Otten
__peter__ at web.de
Sat Feb 5 09:28:05 EST 2005
Alexander Zatvornitskiy wrote:
> Привет Peter!
>
> 31 января 2005 в 09:09, Peter Otten в своем письме к All писал:
> PO> pychecker may help you find misspelled variable names. You have to
> PO> move the code into a function, though:
>
> PO> $ cat epsilon.py
> ...skipped...
> PO> $ pychecker epsilon.py
> PO> epsilon.py:6: Local variable (epselon) not used
>
> Well, I can change it a little to pass this check. Just add "print
> epselon" line.
You are now on a slippery slope. I'd rather think of ways to write my code
in a way for it to succeed or at least fail in an obvious way. I don't
consider a scenario likely where you both misspell a name nearly as often
as you write it correctly, and do that in a situation where the program
enters an infinite loop instead of just complaining with an exception,
which is by far the most likely reaction to a misspelt name.
> I think if as soon as I will make such error, I will write special
> checker. It will take code like this:
>
> def loop():
> #var S,epsilon
> epsilon=0
> S=0
> while epsilon<10:
> S=S+epsilon
> epselon=epsilon+1
> print S
Code not written is always errorfree, and in that spirit I'd rather strive
to write the function more concisely as
def loop2():
s = 0
for delta in range(10):
s += delta
print s
This illustrates another problem with your approach: would you have to
declare globals/builtins like range(), too?
> Such checker will say "error:epselon is not declared!" if I will use
> something not declared. If everything is ok, it will call pychecker.
> Simple and tasty, isn't it?
That your program compiles in a somewhat stricter environment doesn't mean
that it works correctly.
> Of cource, it may be difficult to handle fields of classes:
> MyClass.epsElon=MyClass.epsilon+1
MyClass.epsilon += 1
reduces the risk of a spelling error by 50 percent. I doubt that variable
declarations reduce the likelihood of erroneous infinite loops by even 5
percent.
> but it is solvable, I think. What do you think, is it a good idea?
I suggested pychecker more as a psychological bridge while you gain trust in
the Python way of ensuring reliable programs, i. e. writing small and
readable functions/classes that do one thing well and can easily be tested.
Administrative overhead -- as well as excessive comments -- only serve to
bury what is actually going on.
I guess that means no, not a good idea.
On the other hand, taking all names used in a function and looking for
similar ones, e. g. by calculating the Levenshtein distance, might be
worthwhile...
Peter
More information about the Python-list
mailing list