Metaclass to make all methods of a class thread-safe

Michele Simionato michele.simionato at gmail.com
Tue Sep 28 10:42:17 CEST 2004


Irmen de Jong <irmen at -nospam-remove-this-xs4all.nl> wrote in message news:<41586889$0$568$e4fe514c at news.xs4all.nl>...
> Built-in methods such as?

This is instructive:

>>> class C(object): pass
...
>>> for attr in dir(C): print attr, type(getattr(C,attr))
...
__class__ <type 'type'>
__delattr__ <type 'wrapper_descriptor'>
__dict__ <type 'dictproxy'>
__doc__ <type 'NoneType'>
__getattribute__ <type 'wrapper_descriptor'>
__hash__ <type 'wrapper_descriptor'>
__init__ <type 'wrapper_descriptor'>
__module__ <type 'str'>
__new__ <type 'builtin_function_or_method'>
__reduce__ <type 'method_descriptor'>
__reduce_ex__ <type 'method_descriptor'>
__repr__ <type 'wrapper_descriptor'>
__setattr__ <type 'wrapper_descriptor'>
__str__ <type 'wrapper_descriptor'>
__weakref__ <type 'getset_descriptor'>


For instance object.__new__ is a "builtin_function_or_method"

> About the other objects: I only cared about wrapping class methods.
> Shouldn't I have / should I use something else than FunctionType?

Yes, if you want to wrap staticmethods/classmethods and custom descriptors.
 
> There is one thing though; methods that you're accessing trough the
> class's __dict__ (which is what the meta class is doing, right?)
> are of type <function>, rathar than <instancemethod> which I expected:
> 
>  >>> class A:
> ...  def meth(self): pass
> ...
>  >>> type(A.meth)
>  <type 'instancemethod'>
>  >>> type(A.__dict__['meth'])
>  <type 'function'>
>  >>>
> 
> Why is this?

Google for Raymond Hettinger essay on descriptors and you will have
the answer. There is no real difference between functions and methods,
they are all descriptors and can be converted each other. For instance,
this converts a function to a bound method:

>>> def f(self): pass
...
>>> f.__get__(C(),C) # magically converts the function to a bound method
<bound method C.f of <__main__.C object at 0x403b7f8c>>
>>> f.__get__
<method-wrapper object at 0x403b7f4c>

You should really look at Raymond's essay to understand what is going on
under the cover when you write

>>> C.m = f # magically convert the function to a bound method
>>> C().m
<bound method C.f of <__main__.C object at 0x403b7f0c>>

                Michele Simionato



More information about the Python-list mailing list