Order in metaclass
Peter Otten
__peter__ at web.de
Wed Oct 13 07:50:00 EDT 2004
Bengt Richter wrote:
> Or, an ugly hack that might work for a while, depending on how
> co_names is really generated. It seems in order of occurrence
> (including right hand sides of assignment, but still top down) ...
>
> >>> import sys
> >>> def getnames(): return sys._getframe(1).f_code.co_names
> ...
> >>> def MC(cname, cbases, cdict):
> ... names = cdict.get('ordic',[])
> ... names = [name for name in names if name in cdict]
> ... cdict['ordic'] = dict([(name,i) for i,name in enumerate(names)])
> ... return type(cname, cbases, cdict)
> ...
> >>> class C(object):
> ... __metaclass__ = MC # really a function shortcut
> ... x = 123
> ... y = sys
> ... z = 0
> ... ordic = getnames()
> ...
> >>> C.ordic
> {'ordic': 5, '__module__': 0, '__metaclass__': 1, 'y': 3, 'x': 2, 'z': 4}
A metaclass /function/ and sys._getframe() exercised on a class definition
- I think you have raised the bar for what qualifies as a hack :-)
Peter
More information about the Python-list
mailing list