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
Local static variables
Re: Local static variables
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.
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Local static variables
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.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.