Re: Pl/Python error when import "from __future__"

From: Marco Colombo <pgsql(at)esiway(dot)net>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Pl/Python error when import "from __future__"
Date: 2011-04-01 01:44:07
Message-ID: 4D952DE7.5040908@esiway.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 03/31/2011 09:58 PM, Davi Duarte wrote:
> Hello,
>
> I'm using PL/Python in PostegreSQL 9.0.3 and Python 2.6.5, I want to use
> a feature of Python 3, Python have an option to import a module from
> future version of Python.
>
> In my case, I want to use the Python 3 division module, because it
> returns a float division of integers by defaut, which in Python 2.x only
> returns an integer, then I need use division module of the Python 3.
>
> So to import a module from a future version, simply:
>
> from __future__ import modulename
>
> In my case I'm importing the division:
>
> from __future__ import division
>
> Python must requires that the import be in the first line of code, then
> that is my problem, e.g., when running the function below:
>
> CREATE OR REPLACE FUNCTION test() RETURNS text AS $$
> from __future__ import division
> a = "8/5"
> return eval(a)
> $$ LANGUAGE plpython2u;
>
> returns the following error:
>
> SyntaxError: from __future__ imports must occur at the beginning of the file
>
> But "from __future__ ..." is on first line of code.
>
> Has anyone had this error? and what may be this error? a bug in
> PL/Python? How can I fix this error?
>
> Thanks,
>
> Davi Duarte.

AFAIK, a CREATE FUNCTION in plpython2u adds a python function definition
right before the code you provide (which is the fuction body, or 'suite'
in python parlance):

def function_name(parameter_list):
your_suite

(it does some other mangling to correct indentation, BTW)

As far as the python interpreter is concerned, 'from __future__ import
...' statement is not at the beginning of the program.

I started looking into this some years ago, but at the time the only
solution I managed to design was using some internal interpreter API,
unsupported and subject to change. My idea was to mangle the parse tree,
not the program source: in theory it would be possible to spot the 'form
__future__ import ...' statement and move it at the top. It also avoids
any problem with indentation. At the time there was no "proper" way to
do that, tho.

I'm afraid there's no solution for your problem at the moment. Well, a
workaround is to multiply one of the division arguments by 1.0,
effectively casting it to float. Note this isn't the same of using
float() itself.

>>> a = "1.0*8/5"
>>> eval(a)
1.6

.TM.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David Johnston 2011-04-01 01:57:21 Re: Counting records in a child table
Previous Message Carlo Stonebanks 2011-03-31 23:04:37 Re: Sequence names have 64 character limit?