feature suggestion

flexibal tomerfiliba at hotmail.com
Fri Dec 24 14:08:03 CET 2004

hi there.

i didnt know if i should post it at python-dev or here, so i'll start
here. i'd like to suggest a new language feature for python that allows
you to explicitly declare a variable.

as we all know, just doing
v = 5
declares a new variable named 'v'... but we are people, and we do make
typos... and it's very disturbing to find your program crashing after
two weeks of operation, over a NameError... because a certain branch in
your code, that was previously never taken, had finally been taken.

i've written several large-scale projects in python by now... i find it
excellent for automated testing and other infrastructural needs... but
mistyped variable-, function-, class-, and module- names been a PITA
for me ever since i've started to use python.

python is a scripting language after all, and should preserve its
scripting nature. but adding features that help you verify your python
code should also be included.

BASIC has the "OPTION EXPLICIT" feature that forces you to explicitly
declare all variables, and i see no reason why python should have a
similar mechanism.

either you start python with some commandline switch, or with a
language construct, you should be able to turn on explicit variable

first proposal:
>>> import sys
>>> sys.is_strict = True
>>> decl("x")
>>> x = 5
>>> y = 6
StrictError: name 'y' not explicitly declared

the syntactic format can be debated, of course. here 'decl' is used as
a built-in function that adds the name 'x' to a list of
"explicitly-declared-variables", and when setattr is called, it makes
sure the variable's name is within this list.

this is also fit for dynamic code, but suffers from still having to
execute the code before it is enforced. problems will remain in things

x = 5
if x == 6:
y = 7

second proposal:
syntactic verification, at parsing time. for example:


##decl x
##decl y, z
x = 5
y = 6
z = 8
a = 6

when this program will be ran with the -strict option, like 6th line
will generate a SyntaxError: name 'a' not explicitly declared.

this strategy can verify all sorts of dead-branches, as demonstrated
above, but is not fit for dynamic code.


personally, i like the second proposal more, because it adds no new
language constructs, only a new commandline switch and meta-comments,
and is totally backwards compatible.


More information about the Python-list mailing list