Python is DOOMED! Again!

Ian Kelly ian.g.kelly at gmail.com
Fri Jan 30 22:50:23 CET 2015


On Fri, Jan 30, 2015 at 11:42 AM, Mario Figueiredo <marfig at gmail.com> wrote:
> To be clear, type declarations in Julia, Scala, C have the potential to
> produce side-effects, can result in optimized code and can result in
> compile time errors or warnings. They also affect runtime evaluation as
> you could easily attest if you input a float into a function expecting
> an int, whereas in Python the float will be gladly accepted and will
> only fail at the point in code where its interface won't match the
> statement.

At least for C, as I noted in a previous post, it is simply not true
that they are used for runtime evaluation. For example:

>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> libc.abs(ctypes.c_double(123.456))
2093824448

The C compiler may complain about it, but that's a compile-time static
check, no different from the sort of checks that PEP 484 seeks to add
to Python.

> Meanwhile, type annotations in Python are instead completely ignored by
> the interpreter. They do nothing of the above. They do not participate
> in code generation and execution.

But unlike C, Python lets you easily implement this yourself if you want to.

>>> def runtime_type_check(f):
...   @functools.wraps(f)
...   def wrapper(**args):
...     for arg, value in args.items():
...       if arg in f.__annotations__:
...         if not isinstance(value, f.__annotations__[arg]):
...           raise TypeError("Arg %s expected %s, got %s"
...               % (arg, f.__annotations__[arg].__name__, type(arg).__name__))
...     return f(**args)
...   return wrapper
...
>>> @runtime_type_check
... def add(x:int, y:int) -> int:
...   return x + y
...
>>> add(x="hello", y="world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in wrapper
TypeError: Arg y expected int, got str

(This could of course be extended for positional arguments and more
complex annotations, but I wanted to keep it simple for the purpose of
the example.)



More information about the Python-list mailing list