开发者

Is there a way to give parts of the local namespace to an importee?

a.py:

import b
import c
...
import z

class Foo(object):
    ...

Each of thoses module B-Z needs to use class foo.

Is some way, lik开发者_Python百科e importing, which allows indirect access (e.g. via an object) to all values of all modules A-Z, while still allowing each module B-Z access to A's namespace (e.g. foo).


No. They must each in turn import A themselves.


I still cannot tell what you are trying to do or even asking, but this is my best guess:

Normally, just use classic imports.

IF a module is growing too large, or if you have an extremely good reason to split things up but desire to share the same namespace, you can "hoist" values into a dummy namespace. For example if I had widget.Foo and widget.Bar and wanted them in different files, but I wanted to be able to type Foo and Bar in each file, I would normally have to from widget import Foo and from widget import Bar. If you have MANY of these files (foo.py,bar.py,baz.py,...,zeta.py) it can get a bit unwieldy. Thus you can improve your situation by importing them only once, in widget/__init__.py, and then going from foo import *, from bar import *, ... in each folder just once, and going from widget import * only once in each module. And you're done!... well... almost...

This gets you into a circular import scenario, which you have to be extremely careful of: Circular (or cyclic) imports in Python It will be fine for example if you reference Bar in a function in foo.py, everything is fine because you don't immediately use the value. However if you do x = Bar in foo.py then the value may not have been defined yet!

sidenote: You can programatically import using the __import__ function. If you couple this with os.walk then you can avoid having to type from ... import * for each file in your widget folder. This is a critical and necessary step to avoid bugs down the line.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜