在检查对象的身份时,我会遇到断言错误,因为对象创建代码以一种表示法(base.other_stuff.BarCode)导入对象定义模块,而身份检查代码以另一种表示法(other_stuff.BarCode)导入同一模块。 (请参阅下面的详细信息。)

似乎isinstance()调用对对象定义模块的引用很粘,并且希望以完全相同的符号将其导入。 (我使用的是2.5版。)

我想可以通过在检查身份的代码中更改导入符号来解决此问题,但我担心我会将同一个问题传播到依赖它的其他代码中。而且我敢肯定,一开始我可能应该使用一些更优雅的解决方案。

那么我该如何解决呢?

细节

PythonPath:“ /”,“ / base /”

档案:

/__init__.py
base/__init__.py
base/other_stuff/__init__.py
base/other_stuff/BarCode.py
base/stuff/__init__.py
camp/__init__.py


base / stuff / FooCode.py的文本:

import other_stuff.BarCode as bc

class Foo:
    def __init__(self, barThing):
        assert isinstance(barThing, bc.Bar)


camp / new_code.py的文本:

import base.stuff.FooCode as fc
import base.other_stuff.BarCode as bc

thisBar = bc.Bar()
assert isinstance(thisBar, bc.Bar)
thisFoo = fc.Foo(barThing=thisBar)


这失败了。它可以通过断言测试,但会破坏初始代码中的断言。

但是,当我修改new_code以使用以下命令导入BarCode.py时,它可以工作:

import other_stuff.BarCode as bc


。 。 。因为base /和base / other_stuff都在PythonPath上。

最佳答案

看起来您的<root>/中有<root>/basesys.path,这总是很糟糕。从base / stuff / FooCode.py执行import other_stuff.BarCode as bc时,它会将other_stuff导入为根软件包,但不导入base的子软件包。因此,在执行import base.other_stuff.BarCode as bc之后,您将导入两次BarCode模块:使用other_stuff.BarCodebase.other_stuff.BarCode

最好的解决方案是:


<root>/base(或$ PYTHONPATH)中删除sys.path
在base / stuff / FooCode.py中使用相对导入:from ..other_stuff import BarCode as bc

关于python - Python:导入语句符号中的差异引发的对象身份声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1650603/

10-14 19:29
查看更多