Commit 925bd67c authored by Damien George's avatar Damien George

py/objfun: Support fun.__globals__ attribute.

This returns a reference to the globals dict associated with the function,
ie the global scope that the function was defined in.  This attribute is
read-only but the dict itself is modifiable, per CPython behaviour.
Signed-off-by: default avatarDamien George <damien@micropython.org>
parent 5d68b5e2
......@@ -355,6 +355,10 @@ void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (attr == MP_QSTR___name__) {
dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_get_name(self_in));
}
if (attr == MP_QSTR___globals__) {
mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in);
dest[0] = MP_OBJ_FROM_PTR(self->globals);
}
}
#endif
......
# test the __globals__ attribute of a function
def foo():
pass
if not hasattr(foo, "__globals__"):
print("SKIP")
raise SystemExit
print(type(foo.__globals__))
print(foo.__globals__ is globals())
foo.__globals__["bar"] = 123
print(bar)
try:
foo.__globals__ = None
except AttributeError:
print("AttributeError")
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment