Python and dynamic typing

While reading Typing: Strong vs. Weak, Static vs. Dynamic my mind was jogged by this statement:

Pythonic programming style is to use inheritance primarily for implementation; Python’s name-based polymorphism means that you rarely need to inherit for interface

I was reminded of the Java Toolbox article on Why extends is evil. What implications does the “The fragile base-class problem” have with regard to Pythonic style?

Q. Is Python evil because extension is the only option (there is no such thing as an interface in Python)?

A. No. Python objects can do what that article is talking about: wrap other objects to encapsulate behavior without exposing methods with incorrect semantic meaning.

One thought is that Python developers have no need to explicitly define interfaces, they just write code that implements them. I like less code, but I’m still grappling with the idea that, in Python, there is no easy way to see where an interface change will break other code without writing comprehensive unit tests. With Eclipse a change to the interface and a recompile (automatic) will reveal most if not all breakage points within the application (assuming minimal use of reflection and introspection). One very useful aspect of this behavior in Java is the ability to get an idea of the impact of a given interface change–and Eclipse makes it really easy to see that impact as well as to fix the damage once the change is made. Having said all that, interfaces are no substitute for good unit tests. Ahh, but they sure do provide a nice false sense of security…hey, it compiles. With Python the statement “hey, it starts up” only means that the code needed to get your application started is working. Could a tool be written to test Python code for the type of errors that are exposed by Eclipse when a Java interface changes before the change is resolved in the implementation?

Maybe an “interface testing module” could be written to detect if an object implements a given “interface”? …but now I’m back to writing my interface in code … I guess any comprehensive test suite would most likely have that information anyway.

For reference: encapsulation

Interesting, but not really related:
Why getter and setter methods are evil and More on getters and setters. Future post: how does the getter/setter problem in these articles relate to Pythonic style?

Comments are closed.