Can't make static local variable work

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
liudr
Posts: 211
Joined: Tue Oct 17, 2017 5:18 am

Can't make static local variable work

Post by liudr » Sun Dec 05, 2021 8:00 pm

I have this simple test code that runs on PC Python just fine but produces error on MP:

Code: Select all

def test_local():
    if not hasattr(test_local, "myVar"):
         test_local.myVar = 10
    print(test_local.myVar)
On PC:

Code: Select all

>>> test_local()
10
On MP (ESP32 port 1.17):

Code: Select all

>>> test_local()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in test_local
AttributeError: 'function' object has no attribute 'myVar'
If I attempt to define this static local variable outside the function:

Code: Select all

>>> test_local.myVar=5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'myVar'
So how do I use static local variable in MP? Is it a supported feature?

User avatar
Mike Teachman
Posts: 155
Joined: Mon Jun 13, 2016 3:19 pm
Location: Victoria, BC, Canada

Re: Can't make static local variable work

Post by Mike Teachman » Sun Dec 05, 2021 8:57 pm

Discussed here:
viewtopic.php?t=3368

Post Reply