Skip to content

Instantly share code, notes, and snippets.

@Maltysen
Last active November 28, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maltysen/1beaefa69beac25f11a8 to your computer and use it in GitHub Desktop.
Save Maltysen/1beaefa69beac25f11a8 to your computer and use it in GitHub Desktop.
C++ Templates for Python
def template_specialize(fname, *args):
if fname not in globals():
globals()[fname] = lambda *_, **__: 1/0
def template_specializer(func):
old_func = globals()[fname]
globals()[fname] = lambda *pargs: func(*pargs) if all(isinstance(a, t) for a, t in zip(pargs, args)) else old_func(*pargs)
return func
return template_specializer
@template_specialize('div_fn', int, int)
def iidiv_fn(a,b): return a//b
@template_specialize('div_fn', int, float)
def ifdiv_fn(a,b): return a/b
print div_fn(8, 5)
print div_fn(8, 5.0)
print
@template_specialize('first', (int, float))
def incr(a):
return a + 1
@template_specialize('first', str)
def head(a):
return a[0]
print first(5)
print first(5.3)
print first("sds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment