Skip to content

Instantly share code, notes, and snippets.

@public
Last active June 6, 2021 16:07
Show Gist options
  • Save public/371b9db2e3b9b4fe9fec6aea59ad271d to your computer and use it in GitHub Desktop.
Save public/371b9db2e3b9b4fe9fec6aea59ad271d to your computer and use it in GitHub Desktop.
early binding in Python
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