开发者

Keeping imported modules out of python package namespaces

I've noticed sometimes if you call dir() on a package/module, you'll see other modules in the namespace that were imported as part of the implementation and aren't meant for you to use. For instance, if I install the fish package from PyPI and import it, I see fish.sys, which just refers to the built-in sys module.

My question is whether that's sane and what to do ab开发者_如何学运维out it if it's not.

I don't think the __all__ variable is too relevant, since that only affects the behavior of from X import *. The options I see are:

  • structure your packages better, and at least push the namespace clutter down into submodules
  • use import X as _X in your package to distinguish implementation details from your package API
  • import things from inside your functions (blegh)


My question is whether that's sane

It's sane. Doing import fish adds just one name to your namespace, that is not "namespace clutter". It's pretty much the big idea behind modules, grouping many things under one name!

When you want to know what a module does, look at the documentation or call help, don't do dir.

All names in Python are stored in dictonaries. This means that no matter how many names you see, looking up one of them takes constant time. So there is no speed drawback of any kind either.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜