Files
micropython/tests/micropython/native_marshal.py
Damien George 93692caefa extmod/modmarshal: Support marshal.dumps of functions with children.
This commit adds support to the `marshal` module to be able to dump
functions that have child functions.  For example:

    import marshal

    def f():
        def child():
            return 1
        return child

    marshal.dumps(f.__code__)

It also covers the case of marshalling functions that use list
comprehensions, because a list comprehension uses a child function.

This is made possible by the newly enhanced
`mp_raw_code_save_fun_to_bytes()` that can now handle nested functions.

Unmarshalling via `marshal.loads()` already supports nested functions
because it uses the standard `mp_raw_code_load_mem()` function which is
used to import mpy files (and hence can handle all possibilities).

Signed-off-by: Damien George <damien@micropython.org>
2026-01-27 01:20:36 +11:00

46 lines
853 B
Python

# Test the marshal module in combination with native/viper functions.
try:
import marshal
(lambda: 0).__code__
except (AttributeError, ImportError):
print("SKIP")
raise SystemExit
import unittest
def f_native():
@micropython.native
def g():
pass
return g
def f_viper():
@micropython.viper
def g():
pass
return g
class Test(unittest.TestCase):
def test_native_function(self):
# Can't marshal a function with native code.
code = f_native.__code__
with self.assertRaises(ValueError):
marshal.dumps(code)
def test_viper_function(self):
# Can't marshal a function with viper code.
code = f_viper.__code__
with self.assertRaises(ValueError):
marshal.dumps(code)
if __name__ == "__main__":
unittest.main()