|
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 $ --> |
2 | 2 |
|
3 | 3 | <chapter id="plpython">
|
4 | 4 | <title>PL/Python - Python Procedural Language</title>
|
@@ -213,6 +213,42 @@ def __plpython_procedure_pymax_23456():
|
213 | 213 | above. Use of named parameters is usually more readable.
|
214 | 214 | </para>
|
215 | 215 |
|
| 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 | + |
216 | 252 | <para>
|
217 | 253 | If an SQL null value<indexterm><primary>null value</primary><secondary
|
218 | 254 | sortas="PL/Python">PL/Python</secondary></indexterm> is passed to a
|
|
0 commit comments