Skip to content

Instantly share code, notes, and snippets.

@agumonkey
Last active March 6, 2019 17:11
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 agumonkey/e1f378d8c5cef387b64de33a9309f720 to your computer and use it in GitHub Desktop.
Save agumonkey/e1f378d8c5cef387b64de33a9309f720 to your computer and use it in GitHub Desktop.
metaprogramming (inspired by dave beazley)
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