views:

245

answers:

4

I have a structure such this works :

import a.b.c
a.b.c.foo()

and this also works :

from a.b import c
c.foo()

but this doesn't work :

from a import b.c
b.c.foo()

nor does :

from a import b
b.c.foo()

How can I do the import so that b.c.foo() works?

+1  A: 

In your 'b' package, you need to add 'import c' so that it is always accessible as part of b.

too much php
Then b has to guess all the submodules that you would ever want to use on it? The code is in c, shouldn't there be a better way?
Paul Tarjan
+2  A: 
from a import b
from a.b import c
b.c = c
Alex Martelli
isn't that monkeypatching the code?
Paul Tarjan
Not sure what "monkeypatching the code" means -- it's monkeypatching module (package) b to remedy the fact that it doesn't, apparently, import its own c sub-module.
Alex Martelli
BTW, the intermediate name could also be changed with an `as`, of course, whether you then monkeypatch it back in as `b.c` or not.
Alex Martelli
A: 
import a.b.c
from a import b
b.c.foo()

The order of the import statements doesn't matter.

MizardX
+7  A: 

Just rename it:


from a.b import c as BAR

BAR.foo()
Fred
see newest comment. but indeed, your solution works.
Paul Tarjan