开发者

Python - import error

开发者 https://www.devze.com 2022-12-26 19:02 出处:网络
I\'ve done what I shouldn\'t have done and written 4 modules (6 hours or so) without running any tests along the way.

I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way.

I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass.

/mydir/utils.py imports get_hash() from /mydir/__init__.

/mydir/__init__.py imports SpamClass from /mydir/utils.py.

Both the class and the method work fine on their own b开发者_Python百科ut for some reason if I try to import /mydir/, I get an import error saying "Cannot import name get_hash" from /mydir/__init__.py.

The only stack trace is the line saying that __init__.py imported SpamClass. The next line is where the error occurs in in SpamClass when trying to import get_hash. Why is this?


This is a pretty easy problem to encounter. What's happening is this that the interpreter evaluates your __init__.py file line-by line. When you have the following code:

 import mydir.utils
 def get_hash(): return 1

The interpreter will suspend processing __init__.py at the point of import mydir.utils until it has fully executed 'mydir/utils.py' So when utils.py attempts to import get_hash(), it isn't defined because the interpreter hasn't gotten to it's definition yet.


To add to what the others have said, another good approach to avoiding circular import problems is to avoid from module import stuff.

If you just do standard import module at the top of each script, and write module.stuff in your functions, then by the time those functions run, the import will have finished and the module members will all be available.

You then also don't have to worry about situations where some modules can update/change one of their members (or have it monkey-patched by a naughty third party). If you'd imported from the module, you'd still have your old, out-of-date copy of the member.

Personally, I only use from-import for simple, dependency-free members that I'm likely to refer to a lot: in particular, symbolic constants.


In absence of more information, I would say you have a circular import that you aren't working around. The simplest, most obvious fix is to not put anything in mydir/__init__.py that you want to use from any module inside mydir. So, move your get_hash function to another module inside the mydir package, and import that module where you need it.

0

精彩评论

暂无评论...
验证码 换一张
取 消