Dependency Inversion Principle -- Python Way

Alex Martelli aleaxit at yahoo.com
Mon May 21 17:11:21 EDT 2001


"Sasa Zivkov" <sasha at spuni.is> wrote in message
news:mailman.990465422.19951.python-list at python.org...
> Hi,
>
> I have read some discussions on this mailing list about DIP (dependency
> inversion principle) and theoretically everything is clear to me.
>
> So if we have two classes A and B such that A->B (a depends on B)
> and B->A then we have cyclic dependency.

Yes.  But take care that what defines "a dependency" is not
language-independent.

In Python (and any other signature-based-polymorphism setup,
such as C++ templates!), "uses" does not necessarily create a
dependency.  If all the "using" code asks of the "used" one is
that the latter provide methods x, y, z, ..., with certain sigs,
then the dependency of the "using" code is on the method names
and signatures, _intrinsically_.

> One way to break this cycle is to use DIP.

In pure sig-based pm, as I hope I just showed, the "inversion of
dependency" turns out to be *intrinsic*.  Which is part of the
power of signature-based polymorphism, whether it be in the
friendly guise of Python or the less-friendly one of C++ templates.

> According to DIP we define an abstract interface C such that:
> B uses C
> A implements C
>
> and we finish with acyclic dependencies: A->B, B->C, A->C.
>
>
> Now, I want to ask you about implementation.
>
> 1. Would you really declare class ("interface") C in python ?

Not in Python as it stands today.

> 2. Because python has only implicit interfaces is not is enough just to
>    implement C interface in A ?

There is no "C interface" as a unity, or entity.  Just sets of
methods with signatures.

Which isn't to say it could be even better to HAVE a way to
express, objectify, 'C'.  Though I would not narrowly call it
an 'interface' but a 'protocol', and a more general concept than
'implements' is 'is-adaptable-to'.  See PEP 246, at URL
http://python.sourceforge.net/peps/pep-0246.html, for a
dream-way it could be handled...!-)

> 3. Finally if I decide not to really make C class but only
>    to implement this interface in A I will finish with almost the same
>    situation as at the beggining: two classes A and B where A->B and B->(C
> part of A)
>    I am a little confused at this point :-)  ... it seems like I did
really
> nothing.

In a way, because, in sig-based polymorphism, there WAS no need
to do anything special:-).


But, if you defined a protocol, even if the language itself does not let
you express this crucial design-idea, you would in fact have made a
step forward.  Instead of designing in terms of concrete classes, i.e.,
implementation, you'd have designed in term of the protocol, its
user, and its supplier.  It WOULD be even better if this key design
idea could be expressed directly and explicitly in the language...


Alex






More information about the Python-list mailing list