Hard times with packages and instances

Kay Schluehr kay.schluehr at gmx.net
Thu May 5 11:24:56 EDT 2005


Hi people,

I wonder why the isinstance() function is sensitive about the import
path i.e. the result depends not only on the class and the instance but
also on how a class is imported?

Example:

MyPackage/			Top-level package
      __init__.py		Initialize package
      __me__.py                 Module used for setting Python-path
      A.py                      Use objects of ForeignPackage and
                                subpackages
      ForeignPackage/		Don't touch!
            __init__.py         Initialize package
            B.py                Defines class B1
      MySubPackage/		Subpackage
            __init__.py         Initialize subpackage
	    C.py                Defines instance checker for B1 instances


Provide some implementations:

_____________________________________________________________________________

# MyPackage.__init__.py

import __me__
__me__.setmypath()


# MyPackage.__me__.py

def setmypath():
    import __me__
    import inspect
    import sys
    absfile = inspect.getabsfile(__me__)
    abspath =
"/".join(absfile.split("/")[:-1]+absfile.split("\\")[:-1])
    sys.path.append(abspath)


# MyPackage.A.py

from MySubPackage.C import*
from ForeignPackage.B import*

b1 = B1()
checkInstance(b1)
#print b1.__class__


# MyPackage.ForeignPackage.__init__.py
# left empty

# MyPackage.ForeignPackage.B.py

class B1(object):
    def __init__(self):pass


# MyPackage.MySubPackage.C.py

import MyPackage
import ForeignPackage.B as B
#import MyPackage.ForeignPackage.B as B

def checkInstance(inst):
    if isinstance(inst,B.B1):
        print "class is %s"%inst.__class__
    else:
        raise TypeError,"Instance of unknown class '%s'
found"%inst.__class__

____________________________________________________________________________


No run A.py :

A will call checkInstance with a B1 instance and prints

   "class is <class 'MySubPackage.B.B1'>"

as expected.

But if one comments in the line

  import MyPackage.ForeignPackage.B as B

in module C.py and calls A.py one gets:

Traceback (most recent call last):
...
TypeError: Instance of unknown class '<class 'ForeignPackage.B.B1'>'
found

The class which was expected by the checkInstance() function is

   <class 'MyPackage.ForeignPackage.B.B1'>


I'm curios if someone could explain me the difference between this two
class objects?

Regards,
Kay




More information about the Python-list mailing list