question about importing a package

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 6 01:54:54 EST 2012


On Wed, 05 Dec 2012 20:58:46 -0800, Matt 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 *
> 
> I can't refer to in_foo() and in_bar() without prefacing them with the
> module names. I.e. foo.in_foo() and bar.in_bar() work, but I want to
> import them in the __main__ namespace of sample.py and refer to them as
> just in_foo() and in_bar().

Module `sub_one` has two public names, "foo" and "bar", exactly as you 
say. So when you import * from it, you only get two names. Now, you could 
do any of these inside sample.py:

# 1
from sub_one.foo import in_foo
from sub_one.bar import in_bar


# 2
from sub_one import *
in_foo = foo.in_foo
in_bar = bar.in_foo


Or you could turn to sub_one.__init__ and do this:

# 3
__all__ = ['in_foo', 'in_bar']
from foo import in_foo
from bar import in_bar


or any combination of the above.



-- 
Steven



More information about the Python-list mailing list