Page 1 of 1

Local static variables

Posted: Sun May 14, 2017 12:41 pm
by tenspot
Hi,

I am trying to create a local static variable in a function that will be used as a callback. I have tried the following code, which I know works in Python 2.7 and above, but won't work in MicroPython as it does not support user-defined attributes.

def foo():
if not hasattr(foo, "counter"):
print ("True")
foo.counter = 1
else:
print("False")
foo.counter += 1

print (foo.counter)

I would be grateful if anyone can suggest an alternative way of creating local static variables in a MicroPython function.

Regards,

Mervyn

Re: Local static variables

Posted: Sun May 14, 2017 9:45 pm
by deshipu
Python doesn't have "local static" variables. Please don't abuse the syntax like that, it gives you nothing. Either use a global variable (you can prefix it with your function's name if you are afraid of name collisions) or create a class. If you really want to hide the variable from outside, you can put it in a closure.

Re: Local static variables

Posted: Mon May 15, 2017 8:57 am
by pythoncoder
Standard Python does have "function attributes". This is a rarely used feature not implemented in MicroPython. In my view it's a piece of ancient history; as @deshipu suggests, closures have rendered it redundant.