Stuck with metaclass
Fernando Rodriguez
frr at easyjob.net
Sat Nov 22 12:50:24 EST 2003
Hi,
I have a class Preconditions that has a metaclass (MetaChecker), but I guess I
somehow screwed things up with the metaclass definition...
When I create an instance of Preconditions, I get the doc string instead! =:-O
If I remove the metaclass statemente, everythign works fine.
Any help would be greatly appreciated. O:-)
here's my code:
--------------------------------------------------------------------------------------------------
import inspect
def _isNary(fn,n):
"""
Determines a function has the right 'arity'
"""
args = inspect.getargspec(fn)[0]
if len(args) == n:
return 1
else:
return None
class MetaChecker(type):
"""
Metaclas that checks if all 'public' methods' (those that
don't start with _ are unary functions
"""
def __new__(cls, clsname, bases, attribs):
for name, value in attribs.iteritems():
if name[0:1] != "_" and inspect.isfunction(value):
if not _isNary(value, 1):
try:
src = inspect.getsource(value)
except:
src = None
msg = "%s.%s is not a thunk method!"%(clsname,name)
if src:
msg += "\nOffending source:\n\n%s"%src
raise msg
return type.__new__(cls, name, bases, attribs)
class Preconditions (object):
"""
Can only have thunks.
"""
__metaclass__ = MetaChecker
pass
p = Preconditions()
print p
---------------------------------------------------------------
The result is:
<__main__.__doc__ object at 0x0093E970>
What the heck????????
More information about the Python-list
mailing list