2

The following code works fine in my python IDE:

counter = 1000


def increment():
    global counter
    counter += 1


increment()
print(counter)

But when I copy and paste the code in a pl/python function (as below), it doesn't work.

counter = 1000


def increment():
    global counter
    counter += 1


increment()
plpy.notice(counter)

The error message returned is:

ERROR:  NameError: name 'counter' is not defined
CONTEXT:  Traceback (most recent call last):
  PL/Python function "testing", line 9, in <module>
    increment()
  PL/Python function "testing", line 6, in increment
    counter += 1
PL/Python function "testing"
user275801
  • 1,235
  • 1
  • 10
  • 13
  • I'm not able to find any examples on the internet of the global keyword being used in this way. It seems that the global keyword is only used for bringing plpython function parameters into scope. Does this mean that pl/python isn't really python? Sort of like how javascript isn't really java? – user275801 Aug 24 '18 at 05:51

2 Answers2

0

Ok I've had to change it to this:

varcol = {"counter": 1000}


def increment(varcol):
    varcol["counter"] += 1


increment(varcol)
plpy.notice(varcol["counter"])

Rather awkward, but it looks like the global keyword isn't allowed to be used in the usual way in pl/python. It would be nice if the docs mentioned this...

user275801
  • 1,235
  • 1
  • 10
  • 13
0

You should use one of two dictionaries: SD ("static dictionary") or GD ("global dictionary") which is persisting values between calls to the same function or globally - details here:

  if SD.has_key("someval"):
    someval = SD["someval"]
  else:
    someval = inital_value
    SD["someval"] = someval

Regards, Dejan