-
-
Save Maltysen/1beaefa69beac25f11a8 to your computer and use it in GitHub Desktop.
C++ Templates for 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
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 |
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
@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) | |
@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