declaration of variables?

Andrew Bennetts andrew-pythonlist at puzzling.org
Sat Feb 15 20:20:14 EST 2003


On Sat, Feb 15, 2003 at 06:05:09PM +0100, Andr? Jonsson wrote:
> Being a Python-n00b, in the midst of this ?: discussion, it occurred to me 
> that Python does not require variables be delcared before use.
> 
> Why is this so?  Isn't it very helpful if the compiler complains rather 
> than having strange run-time results?
> 
> Small example:
> 
>     if doStuff(42):
>         value=getNextValue()
>     else:
>         valeu=initialValue      # <-- Note the spelling error.
> 
> Surely, in an elightened language like Python it shouldn't be possible to 
> do this kind of error without the compiler complaining.
> 
> The compiler.compileFile() function doesn't complain either, nor does 
> pychecker seem to. It's almost as if it was by design... is it?

The compiler doesn't warn, but pychecker does:

    bash-2.05b$ cat /tmp/blah.py
    
    def blah():
        if doStuff(42):
            value=getNextValue()
        else:
            valeu=initialValue      # <-- Note the spelling error.
    
        return value
    
    
    bash-2.05b$ pychecker /tmp/blah.py 
    Processing blah...
    
    Warnings...
    
    /tmp/blah.py:3: No global (doStuff) found
    /tmp/blah.py:4: No global (getNextValue) found
    /tmp/blah.py:6: Local variable (valeu) not used
    /tmp/blah.py:6: No global (initialValue) found

Unfortunately, it doesn't seem to warn that "Local variable (value) may not
be defined", but it does warn that "Local variable (valeu) not used", which
is sufficient alarm bells for me.

-Andrew.






More information about the Python-list mailing list