1
0
Fork 0

namespace-inject cleanup

This commit is contained in:
Jörn-Michael Miehe 2023-04-03 22:23:23 +00:00
parent 5ffd522209
commit b43613b457

View file

@ -1,52 +1,45 @@
# import new
from types import FunctionType from types import FunctionType
from typing import Callable
def my_func(pstr: str) -> None: def func1(pstr: str) -> None:
def foo() -> None: def foo() -> None:
print(f"{pstr = }") print(f"{pstr = }")
foo() 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() foo()
def func_test(f: FunctionType) -> None: def func_info(f: Callable) -> None:
print(f"{f.__name__ } = {f}, {f.__code__.co_name = }") print(f"{f.__name__ } = {f}, {f.__code__.co_varnames = }")
f("narf") f("bar")
f("zort") f("baz")
def main() -> None: if __name__ == "__main__":
func_test(my_func) func_info(func1)
func_info(func2)
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)
import json import json
print(json.dumps({ print(json.dumps({
name: repr(getattr(f.__code__, name)) name: repr(getattr(func2.__code__, name))
for name in dir(f.__code__) for name in dir(func2.__code__)
}, indent=2)) }, indent=2))
if __name__ == "__main__":
main()