new-style class instance check

Mike C. Fletcher mcfletch at rogers.com
Sun Apr 11 02:40:01 CEST 2004


Richard Gruet wrote:

>Robert
>
>Thank you for your suggestion.
>But unfortunately, isNewStyleClassInstance(o) must return False for
>*everything but* an instance of a new-style class. If o is e.g. a function:
>def foo(): pass
>foo.__class__.rmo
><built-in method mro of type object at 0x1E0BA9E0>
>
>so isNewStyleClassInstance(foo) would return True !
>  
>
Your problem is that you are using "new style class" to describe what 
you want, and "new style classes" are all over Python, with methods, 
strings, lists, etceteras all being new-style classes in the "proper" 
sense of the term.  So, the canonical "is it a new style class instance" 
function:

def isNewStyleClassInstance( obj ):
    try:
        return isNewStyleClass( obj.__class__ )
    except AttributeError:
        return False
def isNewStyleClass( cls ):
    return isinstance( cls, type )

is going to fail your test because all sorts of things that *you* don't 
consider classes are going to be considered new-style classes (e.g. 
list, tuple, str, and functions) even though they really *are* new-style 
classes.

So, your challenge is to define what *you* mean by new-style classes (as 
distinct from what everyone else means), possibly "new-style but not in 
the built-in module":

def isRichardsNewStyle( obj ):
    return isNewStyleClassInstance( obj ) and type(obj).__module__ != 
'__builtin__'

but that wouldn't catch array.ArrayType and the like which are coded in 
C but not stored in the builtins module.

I'm guessing what you're looking for is "everything that would have had 
a type InstanceType in Python 2.1 and before", but I don't have time to 
track down all the little corner cases for how to implement that, and 
I'd guess you'll find that there's better ways to accomplish what you 
want than using it anyway.  Type-class unification has forever blurred 
the line between class and type, and coding as if it hadn't is just 
going to cause pain IMO.

Good luck,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list