problem with isinstance and relative/absolute import
Eric Brunel
eric.brunel at pragmadev.com
Thu Jun 6 14:57:31 EDT 2002
Sylvain Thenault wrote:
> does someone can explain to me the following test case, or should it be
> considered as a bug ?
>
> [syt at tux syt]$ ls tests/
> __init__.py module2.py module.py
> [syt at tux syt]$ cat tests/__init__.py
> [syt at tux syt]$ cat tests/module.py
> class A: pass
>
> a = A()
>
> [syt at tux syt]$ cat tests/module2.py
> from module import A
>
> b = A()
>
> [syt at tux syt]$ export PYTHONPATH=$PWD
> [syt at tux syt]$ cd tests
> [syt at tux tests]$ python
> Python 2.1.3 (#1, Apr 20 2002, 10:14:34)
> [GCC 2.95.4 20011002 (Debian prerelease)] on linux2
> Type "copyright", "credits" or "license" for more information.
>>>> from module2 import b
>>>> from tests.module import A, a
>>>> isinstance(a, A)
> 1
>>>> isinstance(b, A)
> 0
I already noted this problem. The cause seems to be that in module2.py, you
import A with:
from module import A
which is in turn imported in your main script via:
from module2 import b
But in your main script, you do:
from tests.module import A
This seems to confuse the interpreter which creates two classes named A:
one in the module "module", and one in the module "tests.module", that are
not identified as being the same.
However, when you do:
>>>> from tests.module import A, a
>>>> from tests.module2 import b
the line "from module import A" in module2.py is now executed from the
import "from tests.module2 import b". So the interpreter knows that
"module" is in the same directory than module2.py, and is therefore
correctly identified as being the same than tests.module...
The solution is simple: try to avoid importing the same module in two
different ways. First, it's quite ugly; second, it may confuse the
interpreter...
HTH
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list