]> begriffs open source - ai-pg/blob - full-docs/txt/plpython-funcs.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / plpython-funcs.txt
1
2 44.1. PL/Python Functions #
3
4    Functions in PL/Python are declared via the standard CREATE FUNCTION
5    syntax:
6 CREATE FUNCTION funcname (argument-list)
7   RETURNS return-type
8 AS $$
9   # PL/Python function body
10 $$ LANGUAGE plpython3u;
11
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.
23
24    For example, a function to return the greater of two integers can be
25    defined as:
26 CREATE FUNCTION pymax (a integer, b integer)
27   RETURNS integer
28 AS $$
29   if a > b:
30     return a
31   return b
32 $$ LANGUAGE plpython3u;
33
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():
37   if a > b:
38     return a
39   return b
40
41    assuming that 23456 is the OID assigned to the function by PostgreSQL.
42
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
48    work:
49 CREATE FUNCTION pystrip(x text)
50   RETURNS text
51 AS $$
52   x = x.strip()  # error
53   return x
54 $$ LANGUAGE plpython3u;
55
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)
61   RETURNS text
62 AS $$
63   global x
64   x = x.strip()  # ok now
65   return x
66 $$ LANGUAGE plpython3u;
67
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.