Stuck with metaclass

F

Fernando Rodriguez

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????????
 
B

Bengt Richter

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:
Two suggestions:
For for a more generally useful return value
args = inspect.getargspec(fn)[0] return len(args) == n

and to fix the misleading symptom you observed
return type.__new__(cls, name, bases, attribs)
return type.__new__(cls, clsname, bases, attribs)

(No guarantee that's the end of it ;-)

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top