Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc?

Terry Reedy tjreedy at udel.edu
Mon May 24 14:30:18 EDT 2010


On 5/24/2010 12:56 PM, Nathan Rice wrote:
> I'm trying to do some fairly deep introspection and instrumentation of
> instances and classes at runtime, and in order for everything to be
> properly behaved I need to have radically different behavior in the
> event that the thing passed to me is a wrapped class/instance.  Is there
> a really good way, given an instance of a class, to determine if it is
> wrapped or native?  Currently I check to see if it has __slots__ then
> try to setattr a dummy variable but I imagine there is probably a
> cleaner way.

I am not sure what you mean by 'wrapped'. Your subject line says 
something different. In any case, is your universe *all* Python objects 
or some subset?

Builtin classes, named or not, do not have dotted names

 >>> 1 .__class__
<class 'int'>
 >>> class C: pass

I believe all others do, including C-coded extension classes.

 >>> C().__class__
<class '__main__.C'>

tjr




More information about the Python-list mailing list