question about importing a package

alex23 wuwei23 at gmail.com
Thu Dec 6 07:30:46 CET 2012


On 6 Dec, 14:58, Matt <m... at woodridgeadvisors.com> wrote:
> I have a directory structure that looks like this:
>
> sample.py
> sub_one/
>       __init__.py     # defines only the list    __all__ = ['foo', 'bar']
>       foo.py           # defines the function in_foo()
>       bar.py           # defines the function in_bar()
>
> In sample.py, I have this command at the top:
>
> from sub_one import *
>
> What am I doing wrong?

The statement `from sub_one import *` imports from sub_one/
__init__.py, which only imports the two modules into its namespace,
not their contents. What you need to do is bring into __init__.py
everything you want the star-import to pull into your code:

  __init__.py:
    from foo import *
    from bar import *

  foo.py:
    __all__ = [ 'in_foo' ]
    def in_foo():
      ...

  bar.py:
    __all__ = [ 'in_bar' ]
    def in_bar():
      ...

If you structure is like this, you can restrict which items can be
imported within the defining file. If it doesn't make sense to do it
there, remove __all__ and just import directly in the __init__.



More information about the Python-list mailing list