Wednesday, December 02, 2015

Revisiting an old friend, yet again

The most popular blog post I ever wrote was on a suggested alternative for type hinting in Python. This was likely due to the fact that the blog post was linked in PEP 484 which codified a syntax for type hinting.

The alternative syntax I had been suggesting was to use a clause introduced by a new keyword: where. (I had first discussed this idea more than 10 years ago.)

For example, instead of the approved type hinting syntax

def twice(i: int, next: Function[[int], int]) -> int:
    return next(next(i))

I was suggesting to use something like the following:

def twice(i, next):
        i: int
        next: Function[[int], int]
        returns: int
    return next(next(i))

Similarly, instead of using a comment to introduce type hinting for single variables

x = 3 # type: int

one would have used the following:

x = 3
    x: int

However, this alternative was never considered as a serious contender for type hinting since it was not compatible with Python 2.7, unlike the accepted syntax from PEP 484.

Still, as an experiment, I decided to see if I could use the approach mentioned in my last few blog posts and use an nonstandard where clause.  And, of course, it is possible to do so, and it is surprisingly easy. :-)

The main details are to be found in three  previous blog posts. However, to summarize, suppose you with to use a where clause like the one described above which would not have an effect on the actual execution of the Python program (same as for the current type hinting described in PEP 484). All you need to do is

1. include the line

from __nonstandard__ import where_clause

in your program.

2a) if the program to be run is the main program, instead of running it via


you would do

python my_program

instead, where is in the directory "version 5" of this repository, and the relevant is in "version 6".

2b) If instead of having it run as the main program, you would like to import it, then you would include an extra import statement:

import import_nonstandard
import my_program
# rest of the code

and run this program in the usual way. By importing "import_nonstandard" first, a new import hook is created which pre-processes any modules to be imported afterwards - in this case, to remove the where clause or, as I have described in previous posts, to define new keywords or even an entirely different syntax (French Python).

Note: None of the recent experiments are to be taken as serious proposals to modify Python.
Instead, they are a demonstration of what can be done (often in a surprisingly easy way)
with Python as it exists today.

No comments: