Variable problems in PostgreSQL with language plpython3u
It is necessary to declare a variable within the function. Add &quot;global square&quot; here:
[..]
AS $BODY$

global square

square ='ABC'+square
[..]

You will have to do the same for depthlevel.