From b43613b457ce56e95844c6827f5d1899f91ce7ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Mon, 3 Apr 2023 22:23:23 +0000 Subject: [PATCH] namespace-inject cleanup --- namespace-inject.py | 59 ++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/namespace-inject.py b/namespace-inject.py index d9c4f79..7a0308b 100644 --- a/namespace-inject.py +++ b/namespace-inject.py @@ -1,52 +1,45 @@ -# import new - - from types import FunctionType +from typing import Callable -def my_func(pstr: str) -> None: - +def func1(pstr: str) -> None: def foo() -> None: print(f"{pstr = }") foo() -def my_func2(pstr: str) -> None: +def shoehorn(f: Callable) -> Callable: + code = f.__code__.replace( + co_nlocals=2, + co_varnames=("pstr", "foo"), + ) + + return FunctionType( + name=f.__name__, + code=code, + globals=func1.__globals__, + ) + + +@shoehorn +def func2(pstr: str) -> None: foo() -def func_test(f: FunctionType) -> None: - print(f"{f.__name__ } = {f}, {f.__code__.co_name = }") - f("narf") - f("zort") +def func_info(f: Callable) -> None: + print(f"{f.__name__ } = {f}, {f.__code__.co_varnames = }") + f("bar") + f("baz") -def main() -> None: - func_test(my_func) - - fcode = my_func.__code__.replace( - co_name="foo", - co_qualname="foo", - co_nlocals=3, - co_varnames=("pstr", "foo", "lol") - ) - - f = FunctionType( - name="foo", - code=fcode, - globals=my_func.__globals__, - ) - - func_test(f) +if __name__ == "__main__": + func_info(func1) + func_info(func2) import json print(json.dumps({ - name: repr(getattr(f.__code__, name)) - for name in dir(f.__code__) + name: repr(getattr(func2.__code__, name)) + for name in dir(func2.__code__) }, indent=2)) - - -if __name__ == "__main__": - main()