Explicit variable declaration

Duncan Booth duncan.booth at invalid.invalid
Wed Apr 23 17:10:49 CEST 2008


Steve Holden <steve at holdenweb.com> wrote:

> Filip Gruszczy"ski wrote:
>> Just declaring, that they exist. Saying, that in certain function
>> there would appear only specified variables. Like in smalltalk, if I
>> remember correctly.
>> 
> Icon has (had?) the same feature: if the "local" statement appeared 
then 
> the names listed in it could be assigned in the local namespace, and 
> assignment to other names wasn't allowed.

Python being what it is, it is easy enough to add support for declaring 
at the top of a function which local variables it uses. I expect that 
actually using such functionality will waste more time than it saves, 
but here's a simple enough implementation:

def uses(names):
    def decorator(f):
        used = set(f.func_code.co_varnames)
        declared = set(names.split())
        undeclared = used-declared
        unused = declared-used
        if undeclared:
            raise ValueError("%s: %s assigned but not declared"
               % (f.func_name, ','.join(undeclared)))
        if unused:
            raise ValueError("%s: %s declared but never used"
               % (f.func_name, ','.join(unused)))
        return f
    return decorator

Used something like this:

>>> @uses("x y")
def f(x):
    y = x+1
    return z

>>> @uses("x y z")
def f(x):
    y = x+1
    return z


Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    @uses("x y z")
  File "<pyshell#32>", line 10, in decorator
    raise ValueError("%s: %s declared but never used" % (f.func_name, 
','.join(unused)))
ValueError: f: z declared but never used
>>> @uses("x")
def f(x):
    y = x+1
    return z


Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    @uses("x")
  File "<pyshell#32>", line 8, in decorator
    raise ValueError("%s: %s assigned but not declared" % (f.func_name, 
','.join(undeclared)))
ValueError: f: y assigned but not declared
>>> 




More information about the Python-list mailing list