Python Sanity Proposal: Type Hinting Solution

Marko Rauhamaa marko at pacujo.net
Sat Jan 24 10:27:12 CET 2015


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> Marko Rauhamaa wrote:
>
>>    def weekday(day):
>>        assert isinstance(day, int) and 0 <= day <= 6
>>        ...
>
> [...]
>
> Requiring the type-checker to parse and understand arbitrarily complex
> assertions would require the type-checker to be as complex as Python
> itself:

The static type checker / optimizer would of course be limited to a set
of known fixed expression patterns. More complex expressions would
simply be ignored by it.

Moreover, the type checker would probably operate in a compile-time
environment where you assume "isinstance" and "int" retain their usual
meanings. 

Scheme already employs somewhat analogous dirty tricks like that in its
macro preprocessing.

> Assertions also have the problem that they execute arbitrarily complex
> code at runtime.

Assertions don't *have* to execute anything, anywhere, any time. The
static analysis can decide when executing assertions is worth the
trouble. All of the above can also be done JIT.

> Lastly, this use of assertions clashes with "best practice" for
> assertions. Since assertions may be disabled, you should not use them
> for testing user-supplied arguments. So that means you have to write:
>
> def func(arg):
>     assert isinstance(arg, int)  # satisfy the type checker
>     if isinstance(arg, int):  # support times when assert is disabled
>         ...

I think that's a silly argument. You never second-guess assertions.

> This doesn't apply to annotations:
>
> def func(arg:int):
>     # since this is a public function, not private, we cannot assume the
>     # caller will run the type-checker
>     if isinstance(arg, int):
>         ...

I think that usage is plainly bad style as well. Reminds me of the old
adage:

   Dad is always right, and even when he isn't, he's never wrong.


Marko



More information about the Python-list mailing list