py_compile vs. built-in compile, with __future__

dhyams dhyams at gmail.com
Mon Jun 10 18:27:07 EDT 2013


On Monday, June 10, 2013 4:59:35 PM UTC-4, Terry Jan Reedy wrote:
> On 6/10/2013 11:33 AM, dhyams wrote:
> 
> > The built-in compile() function has a "flags" parameter that one can
> 
> > use to influence the "__future__" mechanism. However,
> 
> > py_compile.compile, which I'm using to byte-compile code, doesn't
> 
> > have an equivalent means to do this.
> 
> 
> 
> That flag was added to compile bacause it is needed to compile 
> 
> expressions and single statements, whether in string or ast form, that 
> 
> use future syntax. It is impossible to include a future statement with 
> 
> either. It is not needed for compiling multiple statements. 
> > Is this by design, or would this be considered a bug?
> 
> 
> 
> Design, not needed.
> 
> 
> 
> > import __future__
> 
> > py_compile.compile("foobar.py",flags=__future__.CO_FUTURE_DIVISION)
> 
> 
> 
> Put the future statement inside foobar.py just as you would do if 
> 
> running it from the command line. Notice that there is no command-line 
> 
> future flag either.
> 
> 
> 
> Terry


I guess I'll have to agree to disagree here...the situation I'm in is that I want a user to be able to write a mathematical plugin with as little effort as possible.  So I want the "from __future__ import division" to be baked into the plugin, without have to require the user to put that bit of confusingness at the top of every plugin they write.  It's a matter of elegance to the end-user, especially because I want to make the plugins as idiot-proof as I can.  It will be common for a user not familiar with python to make the common 1/2 mistake (vs. 1.0/2.0).

Is that not a reasonable use-case?

I added the capability in my local Python tree with two very small modifications to py_compile.py:


Change (I'm leaving out the line numbers because they will be different for different versions of Python).

< def compile(file, cfile=None, dfile=None, doraise=False):
> def compile(file, cfile=None, dfile=None, doraise=False, flags=0):

and

< codeobject = __builtin__.compile(codestring, dfile or file,'exec')
> codeobject = __builtin__.compile(codestring, dfile or file,'exec',flags=flags)

Seems like a reasonable use-case and a correspondingly tiny change to the Python source code base to me...but if no one else sees the value, then I'll just leave it alone.





More information about the Python-list mailing list