[Python-ideas] Python Pragmas

Larry Hastings larry at hastings.org
Sat Mar 15 06:35:57 CET 2008



Recently-ish on c.l.py3k (iirc) folks were discussing how to write a 
script that exited with a human-friendly warning message if run under an 
incompatible version of the language.  The problem with this code:

     import sys
     if sys.version < 3: sys.exit("Sorry, this script needs Python 3000")

is that the code only executes once tokenization is finished--if your 
script uses any incompatible syntax, it will fail in the tokenizer, most 
likely with an error message that doesn't make it particularly clear 
what is going on.


After thinking about the problem for a while, it hit me--this is best 
expressed as a "pragma".  For Python's purposes, I would define a 
"pragma" as an instruction to the tokenizer / compiler, executed 
immediately upon its complete tokenization.  The use case here is

     pragma version >= 3 # python version must be less than 3.0

Again, this would be executed immediately, aborting before the tokenizer 
has a chance to see some old syntax it didn't like.


What else might we use "pragma" for?  Well, consider that Python already 
has two specialized syntaxes that are really pragmas: "from __future__ 
import" and "# -*- coding: ".  I think this functionality would be more 
clearly expressed with a "pragma" syntax, for example:

     pragma encoding latin-1
     pragma enable floatdivision

It's a matter of taste, but I've never liked it when languages hide 
important directives in comments--isn't the compiler supposed to 
*ignore* comments?--nor do I like how "from __future__ import" doesn't 
really have anything to do with importing modules.  Your tastes may vary.


There was some discussion back in 2000 about adding a "pragma" to the
language:

     http://www.python.org/dev/summary/2000-08-2/

It sounds like GvR wasn't wholly against the idea:

     http://mail.python.org/pipermail/python-dev/2000-August/008840.html

But nothing seems to have come of it.  The discussion died out in early
September of 2000, and I didn't find any subsequent revivals.

There was some worry back then that pragmas would be a slippery slope, 
resulting in increasingly elaborate pragma syntaxes until 
we--shudder!--wake up one day and have preprocessor macros.  I agree 
that we don't want to go too far down this slippery slope.  I have some 
specific suggestions on how we could obviate the temptation, but they 
are predicated on having pragmas at all, so I might as well keep quiet 
until such point as pragmas get traction.


If you'd like to discuss this in person--or just give me a good hard 
slap for even suggesting it--I'm bouncing around PyCon until Wednesday 
afternoon.  I'm the guy with the Facebook logos plastered around his person.


Cheers,


/larry/



More information about the Python-ideas mailing list