PEP 3107 and stronger typing (note: probably a newbie question)

sturlamolden sturlamolden at yahoo.no
Sun Jul 8 16:35:55 EDT 2007


On Jun 20, 8:53 pm, Stephen R Laniel <s... at laniels.org> wrote:

> Reading [1], I wonder: why isn't the compiler making better
> use of (purely optional) type labeling? Why not make a compiler
> directive so that
>
> a) it will check the types of all my arguments and return
>    values,

If that is what you want, you can get typechecking using a simple
function decorator:

def typechecked(func):
    types = func.func_defaults
    def decorator(*args):
        if len(args) != len(types):
            raise TypeError, 'Wrong number or arguments, expected %d
got %d' % (len(types),len(args))
        for a,t in zip(args,types):
            if type(t) == type:
                if type(a) is not t:
                    raise TypeError, 'Expected ' + str(t) + ' got ' +
str(type(a))
            else:
                if type(a) is not type(t):
                    raise TypeError, 'Expected ' + str(type(t)) + '
got ' + str(type(a))
        return func(*args)
    return decorator


Now code like this:

@typechecked
def foobar(a = int, b = float, c = tuple):
   return None

or

@typechecked
def foobar(a = int, b = float, c = 1.0):
   return None

Your calls to foobar will be typechecked (at runtime, not statically),
and a TypeError exception thrown if your calling types were
incorrect.


Regards,

Sturla Molden




More information about the Python-list mailing list