Proposal: local variable declarations and type advice

logistix logstx at bellatlantic.net
Tue Feb 26 02:06:41 EST 2002


> 3) (Separate proposal from above): add optional type advice:
>
>      local x(foo)     # advises Python implementation that x will
>                       # only be bound to instances of class foo
>
>    This is called "advice" rather than a "declaration" because it has
>    no defined semantics and the compiler is free to ignore it, except
>    that if the program acts as the advice says it will, it will work.
>
>    Example 1:
>      local x(int)    # advise Python that x is an int
>      x = 3 + 2       # guaranteed to set x = 5 and work as you'd expect
>
>    Example 2:
>      local x(int)
>      x = "banana"    # implementation-dependent behavior
>

The type advice is really impossible in a dynamic language and it's not
going to help out a native compiler anyways.  A better example (than Example
2) of code biting you in the ass is:

def foo(x):
    local y(int)
    y = x

This will only be able to successfully statically analyze if every call made
to foo is passing in a statically typed value.  So for any of the "advice"
to work, all vars need to be typed.  This would remove all dynamic
properties from python, which is probably undesirable.  If you do need/want
to validate the type at runtime, you might as well use the builtin type()
function.  This is exactly the way you have to validate info in "real
languages" like C++ (and I imagine java). RTTI is required if your class
heirarchies get too crazy for static checking (such as a toy lisp
interpreter I wrote, all lisp objects inherited from a base "object" class).

# inline
def foo(x):
    assert type(x) == types.IntType, "Invalid parameter passed to function
foo"
    y = x

# helper functions
def isInt(x):
    assert type(x) == types.IntType, "Invalid value, should be an int"
    return x

def foo(x):
    y = isInt(x)

# or of course a class with Operator Overloading
# won't bore you with implementation





More information about the Python-list mailing list