forcing variable declaration ??

Carl Banks imbosol at aerojockey.com
Tue May 27 14:27:38 EDT 2003


Axel Kowald wrote:
> Hello everybody,
> 
> most of the time it is very convenient that Python doesn't need
> variable declaration, but when writing larger programs it often
> happens to me that I mistype a variable name and thus inadvertently
> create wrong variables that can make debugging unnecessarily
> difficult. Therefore my question:
> 
> Is there a trick/feature/module that allows me to force variable
> declaration in python?

Yes, there's a trick:

    def declare(declaration_list):
        import sys
        vars = sys._getframe(1).f_code.co_varnames
        for v in vars:
            if v not in declaration_list:
                raise DeclarationError, "local variable '%s' not declared" % v

This function makes sure the function's local variables are all
present in the declaration list, otherwise it throws an exception.
DeclarationError is a homemade exception, by the way.  Note that
declaration_list has to be a collection of strings.

*All* local variables appearing in the function, including the
arguments, must be declared in the declaration_list.

If you use this, I suggest you put this function inside an "if
__debug__".  Here is an example of its use:

    def function(a,b,c):
        if __debug__:
            declare(["a","b","c","hello","q","r","s"])
	hello = 1
	q = 2
	...


But I recommend the use of PyChecker instead.  It catches this and
many other errors, and is not intrusive.


-- 
CARL BANKS




More information about the Python-list mailing list