[Tutor] python instances and type

Adam Pridgen atpridgen at mail.utexas.edu
Mon Apr 16 10:27:35 CEST 2007


Hello,

Sorry for the long email, but thanks in advance.

I am not quite sure what is happening, so I have not been able to
adequately seek a solution via Google, so if this answer is fairly
easy to find on Google, let me know.  I am not sure how to produce an
example of my problem without using the python code and classes that I
have, so I will try to compose an effective  theoretical example
below.  If there are any clarifications to be made please let me know.

Basically the problem I am having is obtaining the proper type
identification from a Python object.  So going through the motions,
lets say I have 2 types:

class foo_1:
   data = ""
class foo_2:
  foo_1s={}

Time goes by and some assignments are performed and foo_2 is populated
with some foo_1 objects.  Now, I am using the the function below,
get_class_resolution to get the type of foo_1 and foo_2, and it works
well when I don't perform any black magic voodoo and simply use after
the object is created.

It would return the string "foo_1" for the example below:

x = foo_1()
x.data = "boring"
print type(x), type(x).mro()
<class 'foo_1'> [<class 'foo_1'>]
print get_class_resolution(x)
foo_1


But I need to do black magic voodoo, and when I perform an operation
similar to below
on a foo_2 object the get_class_resolution returns "instance".  In
fact I am expecting it to return foo_1.

foo_2o = foo_2()
foo_2o.foo_1s["boring"] = x
bar = foo_2o.foo_1s.values()[0]
print type(bar), type(bar).mro()
<type 'instance'> [<type 'instance'>, <type 'object'>]
print get_class_resolution(bar)
instance

I am not sure what the difference between the instance vs.  a class,
but I never thought the type of the object was allowed to change. Any
help would be appreciated.


Thanks, Adam

def get_class_resolution(obj):
    '''
        get the first class resolution string for a particular object

        @type obj: Mixed/ Any
        @param obj: this is the object to get the name of.  Good
                    for aiding in the comparison of two objects
                    by name and heirarchy

        @rtype: string
        @return: class name resolution of the object
    '''
    # typical output is "[<class 'class.resolution'> <type 'object'>]"
    print str(type(obj).mro())
    print str(type(obj))
    name = str(type(obj).mro()).split("'")[1]
    if len(name.split(".")) > 1:
        return ".".join(name.split(".")[:-1])
    return name


More information about the Tutor mailing list