Simple case of __init__.py and import giving mysterious module not found

一曲冷凌霜 提交于 2020-08-10 19:31:11

问题


I've tried this from so many different angles but can't sort it out. Must be such a simple case. In Python 3.7.6:

Directory structure:

./modtest/
./modtest/__init__.py
./modtest/test1.py
./modtest/test2.py

test1.py:

import modtest
def x(i):
   print(i)
   y(i)    

test2.py:

def y(i):
   print(i)

__init__.py is an empty file.

When I attempt to run the code:

$ /Users/pitosalas/miniconda3/bin/python /Users/pitosalas/mydev/rsb_py/modtest/test1.py
Traceback (most recent call last):
  File "/Users/pitosalas/mydev/rsb_py/modtest/test1.py", line 1, in <module>
    import modtest
ModuleNotFoundError: No module named 'modtest

From what I read this should've worked. I'm sure there's something trivial wrong!


回答1:


You are importing modtest in test1.py while this module itself resides inside of modtest. This can't be because modest wouldn't have yet been defined and added to the search path. So this is what you should have actually:

./modtest/
./modtest/__init__.py
./modtest/
./modtest/test2.py
./test1.py  # this module must be outside of modtest


来源:https://stackoverflow.com/questions/62366700/simple-case-of-init-py-and-import-giving-mysterious-module-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!