Note that there are some explanatory texts on larger screens.

plurals
  1. POcallable as instancemethod?
    primarykey
    data
    text
    <p>Let's say we've got a metaclass <code>CallableWrappingMeta</code> which walks the body of a new class, wrapping its methods with a class, <code>InstanceMethodWrapper</code>:</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' </code></pre> <p>Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though <code>InstanceMethodWrapper</code> is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it).</p> <p>A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, <code>InstanceMethodWrapper</code> is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much).</p> <p>I also tried some dead-ends. Subclassing <code>types.MethodType</code> and <code>types.UnboundMethodType</code> didn't go anywhere. A little introspection, and it appears they decend from <code>type</code>. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point.</p> <p>Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload