2 44.1. PL/Python Functions #
4 Functions in PL/Python are declared via the standard CREATE FUNCTION
6 CREATE FUNCTION funcname (argument-list)
9 # PL/Python function body
10 $$ LANGUAGE plpython3u;
12 The body of a function is simply a Python script. When the function is
13 called, its arguments are passed as elements of the list args; named
14 arguments are also passed as ordinary variables to the Python script.
15 Use of named arguments is usually more readable. The result is returned
16 from the Python code in the usual way, with return or yield (in case of
17 a result-set statement). If you do not provide a return value, Python
18 returns the default None. PL/Python translates Python's None into the
19 SQL null value. In a procedure, the result from the Python code must be
20 None (typically achieved by ending the procedure without a return
21 statement or by using a return statement without argument); otherwise,
22 an error will be raised.
24 For example, a function to return the greater of two integers can be
26 CREATE FUNCTION pymax (a integer, b integer)
32 $$ LANGUAGE plpython3u;
34 The Python code that is given as the body of the function definition is
35 transformed into a Python function. For example, the above results in:
36 def __plpython_procedure_pymax_23456():
41 assuming that 23456 is the OID assigned to the function by PostgreSQL.
43 The arguments are set as global variables. Because of the scoping rules
44 of Python, this has the subtle consequence that an argument variable
45 cannot be reassigned inside the function to the value of an expression
46 that involves the variable name itself, unless the variable is
47 redeclared as global in the block. For example, the following won't
49 CREATE FUNCTION pystrip(x text)
54 $$ LANGUAGE plpython3u;
56 because assigning to x makes x a local variable for the entire block,
57 and so the x on the right-hand side of the assignment refers to a
58 not-yet-assigned local variable x, not the PL/Python function
59 parameter. Using the global statement, this can be made to work:
60 CREATE FUNCTION pystrip(x text)
64 x = x.strip() # ok now
66 $$ LANGUAGE plpython3u;
68 But it is advisable not to rely on this implementation detail of
69 PL/Python. It is better to treat the function parameters as read-only.