Intellij IDEA 无法识别 python 中本地 class 的导入 3
Intellij idea won't recognize import of local class in python 3
我有一个 python3 脚本,script.py,我想在其中实例化一个 class Foobar,它在 clazz.py 中定义。但是,当我尝试导入时,我得到:
$ python3 script.py
...
SystemError: Parent module '' not loaded, cannot perform relative import
这是我的文件结构:
python_import/
├── __init__.py
├── clazz.py
└── script.py
clazz.py:
class Foobar():
def __init__(self):
print("initialized a foobar")
script.py:
from .clazz import Foobar
foobar = Foobar()
如果我去掉 import
中的 .
就 运行 没问题;但是,如果我这样做,我的 IDE (Intellij IDEA) 会在导入下划红色下划线,并且不会自动完成任何内容。我相信在 python3 中包含 .
是正确的,而且 Intellij 似乎喜欢它,那么为什么我的程序 运行 除非我删除它?
我已阅读http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#import, http://python.readthedocs.org/en/latest/reference/import.html, How to import the class within the same directory or sub directory?, Relative imports in Python 3 and Relative import in Python 3 not working。
我怀疑它可能与 virtualenv 有关,但是 a) 我不明白为什么工作目录不是 PYTHONPATH 的一部分,并且 b) 我不确定如何更改它virtualenv - Intellij 为我设置它。
你的 IDE 喜欢 .
的原因是它知道你的脚本在包 python_import/
中,但是当你 运行 它通过命令行时,解释器什么都不知道关于包,所以相对导入将不起作用。
消除"unresolved reference"的红线错误,详见Unresolved reference issue in PyCharm,一步步完善说明
我有一个 python3 脚本,script.py,我想在其中实例化一个 class Foobar,它在 clazz.py 中定义。但是,当我尝试导入时,我得到:
$ python3 script.py
...
SystemError: Parent module '' not loaded, cannot perform relative import
这是我的文件结构:
python_import/
├── __init__.py
├── clazz.py
└── script.py
clazz.py:
class Foobar():
def __init__(self):
print("initialized a foobar")
script.py:
from .clazz import Foobar
foobar = Foobar()
如果我去掉 import
中的 .
就 运行 没问题;但是,如果我这样做,我的 IDE (Intellij IDEA) 会在导入下划红色下划线,并且不会自动完成任何内容。我相信在 python3 中包含 .
是正确的,而且 Intellij 似乎喜欢它,那么为什么我的程序 运行 除非我删除它?
我已阅读http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#import, http://python.readthedocs.org/en/latest/reference/import.html, How to import the class within the same directory or sub directory?, Relative imports in Python 3 and Relative import in Python 3 not working。
我怀疑它可能与 virtualenv 有关,但是 a) 我不明白为什么工作目录不是 PYTHONPATH 的一部分,并且 b) 我不确定如何更改它virtualenv - Intellij 为我设置它。
你的 IDE 喜欢 .
的原因是它知道你的脚本在包 python_import/
中,但是当你 运行 它通过命令行时,解释器什么都不知道关于包,所以相对导入将不起作用。
消除"unresolved reference"的红线错误,详见Unresolved reference issue in PyCharm,一步步完善说明