Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8f649c9

Browse files
committed
Add documentation why reassigning PL/Python function parameters in the
function body can have undesirable outcomes. (bug #5232)
1 parent 16dc6f0 commit 8f649c9

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

doc/src/sgml/plpython.sgml

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<!-- $PostgreSQL: pgsql/doc/src/sgml/plpython.sgml,v 1.42 2009/12/15 22:59:53 petere Exp $ -->
1+
<!-- $PostgreSQL: pgsql/doc/src/sgml/plpython.sgml,v 1.43 2009/12/19 22:23:21 petere Exp $ -->
22

33
<chapter id="plpython">
44
<title>PL/Python - Python Procedural Language</title>
@@ -213,6 +213,42 @@ def __plpython_procedure_pymax_23456():
213213
above. Use of named parameters is usually more readable.
214214
</para>
215215

216+
<para>
217+
The arguments are set as global variables. Because of the scoping
218+
rules of Python, this has the subtle consequence that an argument
219+
variable cannot be reassigned inside the function to the value of
220+
an expression that involves the variable name itself, unless the
221+
variable is redeclared as global in the block. For example, the
222+
following won't work:
223+
<programlisting>
224+
CREATE FUNCTION pystrip(x text)
225+
RETURNS text
226+
AS $$
227+
x = x.strip() # error
228+
return x
229+
$$ LANGUAGE plpythonu;
230+
</programlisting>
231+
because assigning to <varname>x</varname>
232+
makes <varname>x</varname> a local variable for the entire block,
233+
and so the <varname>x</varname> on the right-hand side of the
234+
assignment refers to a not-yet-assigned local
235+
variable <varname>x</varname>, not the PL/Python function
236+
parameter. Using the <literal>global</literal> statement, this can
237+
be made to work:
238+
<programlisting>
239+
CREATE FUNCTION pystrip(x text)
240+
RETURNS text
241+
AS $$
242+
global x
243+
x = x.strip() # ok now
244+
return x
245+
$$ LANGUAGE plpythonu;
246+
</programlisting>
247+
But it is advisable not to rely on this implementation detail of
248+
PL/Python. It is better to treat the function parameters as
249+
read-only.
250+
</para>
251+
216252
<para>
217253
If an SQL null value<indexterm><primary>null value</primary><secondary
218254
sortas="PL/Python">PL/Python</secondary></indexterm> is passed to a

0 commit comments

Comments
 (0)