Possible Duplicate:
Importing modules: __main__ vs import as module
I am aware that in most cases isinstance
is not needed or should be avoided (e.g., Is this use of isinstance pythonic/"good"?). However, sometimes it is what I need.
In both Python 2.6, 2.7, and 3.2, however, I have noticed the following irregularity in how isinstance
works between execution in doctests and normal execution.
For example, I expect the following behavior, where isinstance
is ambivalent to whether I am using qualified or unqualified names:
import collections
from collections import OrderedDict
assert isinstance(collections.OrderedDict(), collections.OrderedDict) == True
assert isinstance(collections.OrderedDict(), OrderedDict) == True
The same code, executed within a Doctest, works just the same.
However, if I define a class within a module named "isinstanceTest.py" and define a function within the same module that uses isinstance
to match that class, things get more interesting. The following doctest is written to pass. I am using the unittest.TextTestRunner
as I routinely gather and run my doctests and unittests across many modules together in one suite.
import unittest, doctest
import collections
class A: pass
def isinstance_A(arg):
'''
>>> import isinstanceTest
>>> isinstanceTest.isinstance_A(isinstanceTest.A())
True
>>> isinstance_A(A())
True
>>> isinstanceTest.isinstance_A(A())
False
>>> isinstance_A(isinstanceTest.A())
False
'''
return isinstance(arg, A)
if __name__ == '__main__':
l = doctest.DocTestSuite(__name__)
runner = unittest.TextTestRunner()
runner.run(l)
Notice that the last two doctest statements, where both qualified and unqualified names are used, produce unexpected results.
If, while in the directory where "isinstanceTest.py" lives, I open an interpreter and execute equivalent commands, results are as expected:
Python 3.2.3 (default, May 3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import isinstanceTest
>>> from isinstanceTest import *
>>> isinstanceTest.isinstance_A(isinstanceTest.A())
True
>>> isinstance_A(A())
True
>>> isinstanceTest.isinstance_A(A())
True
>>> isinstance_A(isinstanceTest.A())
True
So while this behavior is consistent and localized to running doctests in test suites (and I have coded around it as necessary, and generally only use qualified names in doctests anyways), the larger question is: is this a documented limitation of doctests (I have not yet found any docs that mention this), or is this a bug?