Last active
March 6, 2019 17:11
-
-
Save agumonkey/e1f378d8c5cef387b64de33a9309f720 to your computer and use it in GitHub Desktop.
metaprogramming (inspired by dave beazley)
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 dec(*a, **k): | |
print(a,k) | |
return a[0] if a else lambda self: self | |
def debug(f, pre='[debug]', indent='.', inc=1): | |
depth = 0 | |
def _(*a,**k): | |
nonlocal indent | |
nonlocal depth | |
ind = indent*depth | |
print(pre, ind, f, a, k) | |
depth += inc | |
r = f(*a, **k) | |
print(pre, ind, r) | |
depth -= inc | |
return r | |
return _ | |
class Meta(type): | |
def __new__(mcs, name, bases, dct): | |
print(type(dct), dct) | |
new = {} | |
for k in dct: | |
if callable(dct[k]): | |
print('tracable',k) | |
dct[k] = debug(dct[k]) | |
else: | |
print('else',k) | |
if not k.startswith('__'): | |
new['get_'+k] = lambda self: (self, getattr(self,k)) | |
print(new) | |
return type.__new__(mcs, name, bases, {**dct,**new}) | |
class M(metaclass=Meta): | |
x = 1 | |
def fact(self,n): | |
if n < 2: | |
return 1 | |
else: | |
return n*self.fact(n-1) | |
@dec | |
def f(self): | |
return self | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment