Last active
June 6, 2021 16:07
-
-
Save public/371b9db2e3b9b4fe9fec6aea59ad271d to your computer and use it in GitHub Desktop.
early binding in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from types import FunctionType, CellType | |
from typing import Any, Callable, TypeVar, Union | |
F = TypeVar("F", bound=Union[FunctionType, Callable[..., Any]]) | |
def bind(wrapped: F) -> F: | |
new_globals = wrapped.__globals__.copy() | |
new_closure = [CellType(cell.cell_contents) for cell in wrapped.__closure__ or []] | |
return FunctionType( | |
wrapped.__code__, | |
new_globals, | |
wrapped.__name__, | |
wrapped.__defaults__, | |
tuple(new_closure), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment