0

I am setting up a function where recursive action is relevant. The function basically maps two floats according to a rule and then returns a string. The code below is stripped for the actual function, but it should serve as a relevant code example (full code available). The original code (python 2.7) works fine, so I am thinking that there is something about the language, plpython3u, used in PostgreSQL which messes it up.

I imagine this is related to local variables and global variables. I would have thought the variables remained local, but it does not look that way. Is there a way to work around this?

Running the function I get an error message indicating that a variable has already been

ERROR:  UnboundLocalError: local variable 'square' referenced before assignment
CONTEXT:  Traceback (most recent call last):
  PL/Python function "qdgc_get_recursivestring", line 3, in <module>
    square ='ABC'+square
PL/Python function "qdgc_get_recursivestring"
SQL state: 38000

Function:

CREATE OR REPLACE FUNCTION public.qdgc_get_recursivestring(
    lon_value double precision,
    lat_value double precision,
    depthlevel integer,
    square text)
    RETURNS text
    LANGUAGE 'plpython3u'
    COST 100
    VOLATILE PARALLEL UNSAFE

AS $BODY$

square ='ABC'+square

depthlevel = depthlevel -1

if depthlevel<1:
    return square
else:
    return qdgc_get_recursivestring(lon_value,lat_value,depthlevel,square)
  
$BODY$;
1
  • Have you tried naming the function argument differently, say square_ and hence square = 'ABC' +square_. Similar for other arguments Commented Jan 13, 2021 at 20:05

1 Answer 1

2

It is necessary to declare a variable within the function. Add "global square" here:

[..]
AS $BODY$

global square

square ='ABC'+square
[..]

You will have to do the same for depthlevel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.