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

sturlamolden sturlamolden at
Sun Jul 8 22:35:55 CEST 2007

On Jun 20, 8:53 pm, Stephen R Laniel <s... at> 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 ' +
                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:

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


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


Sturla Molden

More information about the Python-list mailing list