Reputation:
Imagine a module called base
with a class called Base
in it.
Now inside an other module, called sub
, inherit a class Sub
from Base
:
import base
class Sub(base.Base):
pass
Now what if we add a third class, that inherits from Sub
and takes a parameter that has to be type of Base
or one of it's subclasses:
import sub
class Deep(sub.Sub):
def __init__(self, parent):
if isinstance(parent, sub.base.Base):
pass
Going deeper and deeper down in the inheritance tree, the path to Base
will become thedeepest.deeperanddeeper.reallydeep.deep.sub.base.Base
, which nobody would like.
I could of course just do from base import *
and from sub import *
and then just use Base
, but is there a way to import so that I can use the prefix of ONLY the original module of my class?
For example:
import deep
class ReallyDeep(deep.Deep):
def __init__(self, parent):
# I know my polymorphism, this is just an example.
if isinstance(parent, sub.Sub):
pass
elif isinstance(parent, base.Base):
pass
Upvotes: 0
Views: 138
Reputation: 2254
Modules in Python are like singletons, they only get imported once, so
import base
import deep
class ReallyDeep(deep.Deep):
def __init__(self, parent):
if isinstance(parent, base.Base):
pass
Is absolutely no problem at all, in fact, it's the best way to do it.
What delnan means is that in most cases deeply nested inheritance trees are a sign of bad design. As with any rule, there are exceptions. But in general avoiding deeply nested trees will make your code more understandable, easier to test and therefore easier to maintain.
Upvotes: 1