简体   繁体   English

从模块导入功能失败,但是可以导入类

[英]Importing a function from a module fails, but classes can be imported

I have a package with several nested modules: 我有一个带有几个嵌套模块的软件包:

somepackage/
  module1/
    __init__.py
    module2/
      __init__.py
      to_be_imported.py
setup.py

I have installed this package with python setup.py develop . 我已经使用python setup.py develop安装了此软件包。 The to_be_imported.py file contains a few classes and a method (after the classes, since the method uses some classmethods of the classes). to_be_imported.py文件包含一些类和一个方法(在类之后,因为该方法使用了类的某些类方法)。 After opening an IPython console, the following import works: 打开IPython控制台后,将执行以下导入:

from somepackage.module1.module2.to_be_imported import SomeClass

but this one fails with ImportError: 但是这失败,并出现ImportError:

from somepackage.module1.module2.to_be_imported import my_method

Moreover, if I import the file as 此外,如果我将文件导入为

from somepackage.module1.module2 import to_be_imported

and print the imported file content, it prints my_method too! 并打印导入的文件内容,它也打印my_method

I am confused about what causes the import error, does anybody encountered such problems? 我对导致导入错误的原因感到困惑,有人遇到过此类问题吗?

Note that module2 is a misnomer , as it isn't actually a module but a subpackage. 请注意, module2用词不当 ,因为它实际上不是模块,而是子包。

You have access to SomeClass because it has been imported from to_be_imported into module2.__init__.py . 您可以访问SomeClass因为它已从to_be_imported导入到module2.__init__.py You can open module2.__init__.py to confirm this. 您可以打开module2.__init__.py进行确认。

To access that function, you should specify the full path: 要访问该功能,您应该指定完整路径:

from somepackage.module1.module2.to_be_imported import my_method

Or have it imported into module2.__init__.py to use the shorter path. 或者将其导入module2.__init__.py以使用较短的路径。

As it turns out, my problem was that my module was cached into my IPython session. 事实证明,我的问题是我的模块已缓存到我的IPython会话中。 I added my_method later, so the cached version did not contain it, but when I printed the file, it printed the newest version. 我后来添加了my_method ,因此缓存版本不包含它,但是当我打印文件时,它打印了最新版本。 More on the topic: Prevent Python from caching the imported modules 有关主题的更多信息: 防止Python缓存导入的模块

To summarize: a console restart is all I needed. 总结一下:我需要重启控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM