Skip to content

Instantly share code, notes, and snippets.

@agoose77
Created June 20, 2023 09:35
Show Gist options
  • Save agoose77/bd20059890bde3e17b88e1d162d9806c to your computer and use it in GitHub Desktop.
Save agoose77/bd20059890bde3e17b88e1d162d9806c to your computer and use it in GitHub Desktop.
import types
import inspect
def impl(x, *, y, z=None):
print(x, y, z, "impl")
def dispatch(x, y, z):
print(x, y, z, "dispatch")
def copy_signature(source, dest):
dest_code: types.CodeType = dest.__code__
source_code: types.CodeType = source.__code__
assert dest_code.co_kwonlyargcount == 0
assert dest_code.co_posonlyargcount == 0
assert dest_code.co_varnames == source_code.co_varnames
new_dest_code = dest_code.replace(
co_argcount=source_code.co_argcount,
co_posonlyargcount=source_code.co_posonlyargcount,
co_kwonlyargcount=source_code.co_kwonlyargcount,
)
new_dest = types.FunctionType(
new_dest_code,
source.__globals__,
dest.__name__,
source.__defaults__,
source.__closure__,
)
new_dest.__kwdefaults__ = source.__kwdefaults__
return new_dest
dispatch_like_impl = copy_signature(impl, dispatch)
impl(1, y=2)
dispatch_like_impl(1, y=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment