diff options
author | Damien George <damien@micropython.org> | 2025-01-20 22:23:48 +1100 |
---|---|---|
committer | Damien George <damien@micropython.org> | 2025-02-11 16:51:50 +1100 |
commit | ceb8ba60b4fea0c32e4977d0e45d5c0203b27b34 (patch) | |
tree | 9c100e265c53509822ecc08155545701a370db6f /tests/basics/fun_code.py | |
parent | 62e821ccb82fd8362a8198ad59ccb51b8a5c441e (diff) | |
download | micropython-ceb8ba60b4fea0c32e4977d0e45d5c0203b27b34.tar.gz micropython-ceb8ba60b4fea0c32e4977d0e45d5c0203b27b34.zip |
py/objfun: Implement function.__code__ and function constructor.
This allows retrieving the code object of a function using
`function.__code__`, and then reconstructing a function from a code object
using `FunctionType(code_object)`.
This feature is controlled by `MICROPY_PY_FUNCTION_ATTRS_CODE` and is
enabled at the full-features level.
Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'tests/basics/fun_code.py')
-rw-r--r-- | tests/basics/fun_code.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/tests/basics/fun_code.py b/tests/basics/fun_code.py new file mode 100644 index 0000000000..59e1f7ec04 --- /dev/null +++ b/tests/basics/fun_code.py @@ -0,0 +1,36 @@ +# Test function.__code__ attribute. + +try: + (lambda: 0).__code__ +except AttributeError: + print("SKIP") + raise SystemExit + + +def f(): + return a + + +ftype = type(f) + +# Test __code__ access and function constructor. +code = f.__code__ +print(type(ftype(code, {})) is ftype) + +# Test instantiating multiple code's with different globals dicts. +code = f.__code__ +f1 = ftype(code, {"a": 1}) +f2 = ftype(code, {"a": 2}) +print(f1(), f2()) + +# Test bad first argument type. +try: + ftype(None, {}) +except TypeError: + print("TypeError") + +# Test bad second argument type. +try: + ftype(f.__code__, None) +except TypeError: + print("TypeError") |