PEP 312 (and thus 308) implemented with a black magic trick
Raymond Hettinger
vze4rx4y at verizon.net
Mon Mar 17 20:19:24 EST 2003
> class DirtyTrick(type):
> """Cooperative metaclass that looks at the source code of its
instances
> and replaces the string '~' with 'lambda :' before the class
creation"""
> def __new__(meta,name,bases,dic):
> for attr in dic.values():
> if inspect.isfunction(attr):
> code=inspect.getsource(attr)
> if code.find('~')==-1: continue # no '~' found, skip
> code=code.replace('~','lambda :')
> code=dedent(code)+'\n'
> exec code in __main__.__dict__,dic # modifies dic
> return super(DirtyTrick,meta).__new__(meta,name,bases,dic)
>
> # a convenient base class:
>
> class RecognizesImplicitLambdas:
> "Children of this class do recognize implicit lambdas"
> __metaclass__=DirtyTrick
Dear Dr. Strangelove,
You are a dangerous man.
I'm glad you're on our side.
You are on our side, aren't you?
curiouser-and-curiouser-ly yours,
Raymond Hettinger
More information about the Python-list
mailing list