Local static variables

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
tenspot
Posts: 2
Joined: Sat Aug 27, 2016 10:11 am

Local static variables

Post by tenspot » Sun May 14, 2017 12:41 pm

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

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: Local static variables

Post by deshipu » Sun May 14, 2017 9:45 pm

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.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Local static variables

Post by pythoncoder » Mon May 15, 2017 8:57 am

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.

Post Reply