Python Feature Request: Explicit variable declarations
samjnaa at gmail.com
Sun Apr 15 05:50:08 CEST 2007
On Apr 14, 3:56 pm, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
> for prior discussion. The request is sane, but is also incomplete: there
> is no syntax suggested for the actual declarations of local variables,
> and no discussion whether this is meant to apply to local variables
> only, or also to global variables and object attributes.
I suggest that the C syntax be followed:
int a, b, c
a = "foo" should raise a TypeError
But as has been pointed out in the intervening messages which are
slightly OT, the line int a, b, c should mean:
"a, b and c are meant to be labels of integer objects so don't allow
them to be labels of other kinds of objects without redeclaration",
and NOT the following:
"create three memory spaces for integers with labels a, b and c"
as it would be in C. This ensures that Python's behaviour of:
>>> a = 2
>>> b = a
>>> a is b
continues even after int a, b. If the C meaning were taken, a is b
would never be True.
I do not see why this cannot be applicable to global variables also.
When explicit type declarations is enabled, no label can be used
implicitly for an object unless it has been declared that that label
is meant for that kind of object. If that label is reassigned to an
object of a different type, a TypeError should be raised. If a label
that has not been declared is used for an object, a
VariableNotDeclaredError should be raised.
This can be used for object attributes also. When a programmer creates
a class, he would be expected to type-declare the members.
This also means that function arguments and return values should be
def bool printNameAndAge ( str name, int age ) :
This option should be set for each source file. Otherwise it will
raise errors in modules which were written without type declaration
(and maybe in modules written in C too ??).
I realize this may be a big thing to include in a language which has
been traditionally dynamically-typed, but it can ease transitions to
lower-level languages like C, especially since one of the most
important uses of Python is learning programming. It is also useful to
pure Python programmers as said above for error-catching.
More information about the Python-list