开发者

What's the benefit of allowing python files to import themselves

I can't tell you how many times I've been bitten by accidentally naming my file like something I'm trying to import, resulting in python importing the file. This example should show what I'm talking about (my first example didn't work) if / is in PYTHONPATH:

/foo
  __init__.py
/test
  foo.p开发者_运维问答y

__init__.py

def do_thingy():
    print "Swosh!"

foo.py

from foo import * # Whops! Self include. Happy debugging.

do_thingy() # Not imported. You fail.

django seem to silently fail when applications, modules, plugins have this error, and the go to method of debugging that (I've been told) is to go to shell and import everything until you find the thing that's broken.

Is there any actual use for recursive imports?


Python namespaces require each name to be distinct. Any time you import a module it is always imported into the global namespace. On the front end, these are just simple assignments. If you import something that collides with a name that is already there, it will silently replace the reference to which the name is assigned.

You wouldn't want Python to "remind" you every time you re-assigned a variable, so why would you want it to do the same for a module import?

Case in point:

import foo as bar
bar = None

Guess what? You just replaced the module object that was assigned to bar with the value None.

And finally, to answer your question: Recursive imports are never a good idea because they are confusing at best and dangerous at worst.


No, there isn't a use for importing yourself. But there also isn't a use for having two things that could be imported by the same name, so there's no point in detecting the case you've given and treating it specially.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜