My problem has to do with exec, import and globals
For ease of illustration, I create a file named code.py, the content of which being:
Code: Select all
class A:
pass
a=A()
a.b=1
def toggle():
a.b*=-1
toggle()
Code: Select all
MicroPython v1.10-131-g952139904 on 2019-02-26; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> def do(): exec(open("code.py").read())
...
>>> do()
>>> dir()
['__name__', 'toggle', 'a', 'do', 'A']
>>> a.b
-1
>>>
However, if I create a file named make.py, the content of which being:
Code: Select all
def do():
exec(open("code.py").read())
def do2():
exec(open("code.py").read(), globals())
Code: Select all
MicroPython v1.10-131-g952139904 on 2019-02-26; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> from make import do
>>> do()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "make.py", line 1, in do
File "<string>", line 10, in <module>
File "<string>", line 8, in toggle
NameError: name 'a' isn't defined
>>> dir()
['__name__', 'toggle', 'a', 'do', 'A']
>>>
If I restart MicroPython and type:
Code: Select all
MicroPython v1.10-131-g952139904 on 2019-02-26; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> from make import do2
>>> do2()
>>> dir()
['__name__', 'do2']
>>> a.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' isn't defined
>>>
Q: Could someone help me understand the underlying mechanisms of exec and import?
PS: I have noticed that def func(): exec('a=2') under MicroPython does the same job as def func(): exec('a=2', globals()) under CPython 3: executing func() will create a variable a, the value of which is 2, in the global namespace.
Q: Why globals() can be omitted under MicroPython for such an example?