← index #15883Issue #937
Related · high · value 0.417
QUERY · ISSUE

function locals() return the same result as globals()

openby ChipedMenopened 2024-09-20updated 2026-03-24
bugpy-coreproposed-close

Port, board and/or hardware

ESP-01 (ESP8266 with 1M)

MicroPython version

MicroPython v1.24.0-preview.286.g042693496 on 2024-09-04; ESP module with ESP8266

Reproduction

def test():
    global h
    h += 1 # modify global var
    x = 5
    print('x =',x)
    if globals()==locals():
        print('locals() and globals() return the same result')
    else:
        print('ok')

h=0
x=10
print('--- Global vars ---')
print('h =',h)
print('x =',x)
print('-----Locals--------')
test()
print('--- Global vars ---')
print('h =',h)
print('x =',x)

Expected behaviour

Here is correct output, seen with Python 3.10.11:

--- Global vars ---
h = 0
x = 10
-----Locals--------
x = 5
ok
--- Global vars ---
h = 1
x = 10

Observed behaviour

--- Global vars ---
h = 0
x = 10
-----Locals--------
x = 5
locals() and globals() return the same result
--- Global vars ---
h = 1
x = 10

Additional Information

No, I've provided everything above.

Code of Conduct

Yes, I agree

CANDIDATE · ISSUE

Obscure bug with locals not captured by function

openby dpgeorgeopened 2014-10-26updated 2024-08-28
bug

This is a bug for the record. It exists because a compiled bytecode function captures only its globals, not its locals. The only way I can make the bug appear (ie the only time a function needs to know the locals it was compiled in context of) is using the builtin compile function, and execute pre compiled code within another module, as follows.

Put this in t1.py:

x = 1
import t2
c = compile('print(x)', 'me', 'exec')
t2.C().ex(c)

and this in t2.py:

x = 2
c = compile('print(x)', 'me2', 'exec')
class C:
    x = 3
    exec('print(x)')
    exec(c)
    def ex(self, c):
        exec(c)

Then run micropython t1.py. Check against CPythons output.

The above code tests more than just this bug, in order that one can see exactly what contexts are used where.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied