2

As explained here, when importing the same module differently (which might be possible because of the system path configuration) it's members are duplicated, causing a behavior which I would consider undesired.

Here's an example:

>>> import PIL.Image as A
>>> A
<module 'PIL.Image' from '/.../python2.7/site-packages/PIL/Image.py'>
>>> import Image as B
>>> B
<module 'Image' from '/.../python2.7/site-packages/PIL/Image.py'>
>>> B.Image
<class Image.Image at 0x7f066410b9a8>
>>> A.Image
<class PIL.Image.Image at 0x7f06640cd120>
>>> A.Image==B.Image
False
>>> isinstance(A.Image(),B.Image)
False
>>> isinstance(B.Image(),A.Image)
False

Is there a reason for this behavior?

Community
  • 1
  • 1
Manux
  • 3,643
  • 4
  • 30
  • 42

1 Answers1

2

This is because PIL is weird. Most Python packages are not available through different names like this. Stick to one way of importing PIL, or don't use isinstance and you'll be fine.

I don't the answer to why Python doesn't detect that the two path actually lead to the same file, and give you the same module. This is the way Python does it, and it can lead to problems sometimes.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 2
    Yes, but it's not a problem proper to PIL, it's a problem proper to the way CPython imports it's modules, and I wondered if it was considered normal behavior. If I stick to a way of importing PIL, and other libraries which I use do it another way, it's not always trivial to find. – Manux Jun 28 '12 at 15:44
  • @Manux: Ned is right – this *is* a problem specific to PIL. Python uses the fully qualified module name as the key to decide if a module is already known, and as long as there is only one name for each module, you won't have a problem. I don't know any other package that features importing the same module underr two different names. – Sven Marnach Jun 28 '12 at 16:49