Import order question

Michael Torrie torriem at gmail.com
Tue Feb 18 17:06:39 EST 2014


On 02/17/2014 06:01 AM, Nagy László Zsolt wrote:
> I have a class hierarchy like this:
> 
> Widget <- VisualWidget <- BsWidget
> 
> and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc.
> 
> Widgets can have children. They are stored in a tree. In order to manage 
> the order of widgets, I need methods to append children. (And later: 
> insert or prepend because they also have an order). So I would like to 
> have methods like this:
> 
> BsWidget.AppendNavbar(....)
> BsWidget.AppendRow(...)

Why not just take advantage of duck typing and have a generic append()
method that takes any kind of widget.  As long as the widget supports
the method calls that BsWidget needs to make on it, you have zero need
of imports in BsWidget.  There's really no need to import other parts of
your widget hierarchy. That is only necessary for the module that
instantiates the objects.

This is one feature of Python I really like and use a lot.  The ability
to completely decouple code units.  Of course you can do similar things
in Java and C++ by using abstract base classes and interfaces.




More information about the Python-list mailing list