Reputation: 18874
I often find myself importing classes from modules that only differ in the last part of their namespace, e.g:
from a.b.c.d import Class1
from a.b.c.e import Class2
from a.b.c.f import Class3
Is there some way for me to type the common a.b.c.
part just once?
I know that if they all had exactly the same namespace, i.e.
from a.b.c import Class1
from a.b.c import Class2
from a.b.c import Class3
Then I could just type
from a.b.c import (Class1, Class2, Class3)
So for my first example, I tried things like
from a.b.c import (d.Class1 as Class1,
e.Class2 as Class2,
f.Class3 as Class3)
... but that didn't work.
Any tips would be greatly appreciated.
Upvotes: 3
Views: 95
Reputation: 77892
If a
is one of your own packages (or if you willing and abale to maintain a fork...) you can use the a.b.c
package as a facade:
# a/b/c/__init__.py
from d import Class1
from e import Class2
from f import Class3
Then:
# client code:
from a.b.c import Class1, Class2, Class3
will work.
Upvotes: 3
Reputation: 1121524
No, there is no syntax to import nested items as local names like that.
You could import the different modules, then assign to local names:
from a.b.c import d, e, f
Class1, Class2, Class3 = d.Class1, e.Class2, f.Class3
del d, e, f
but that's no more readable or concise.
Upvotes: 3