Are assert checks unpythonic? (was: Passing objects to a function)

Andrew Bennetts andrew-pythonlist at puzzling.org
Tue May 11 19:07:28 EDT 2004


On Tue, May 11, 2004 at 03:03:35PM +0200, Holger Türk wrote:
[...]
>   That's my problem with foo-like objects implementing varying
> interfaces that aren't checked. Why isn't there a superclass "FileLike"
> with the standard methods that all raise NotImplementedError, "method
> bar"? So when NotImplementedError is raised, it's absolutely clear

Because inheritance isn't the only way to do polymorphism.

If I have an object with 'write' and 'close' methods, then I expect there
are plenty of functions that that will just fine with.  Having to declare
that it inherits from "FileLike" isn't right -- it doesn't implement even
half of FileLike's methods.  Raising NotImplementedError isn't significantly
better than AttributeError here.  If you need to check that the object
has 'write' and 'close' attributes before you get half-way through the
function, then first do:

    write = obj.write
    close = obj.close

This will raise an AttributeError immediately, or else give you variables
you can use later in the function.

There are more formal approaches, such as Zope 3's interfaces (although Zope
3 then uses them to support stuff like object adaption, rather than just as
a tool to verify that your arguments have the behaviour you expect).

-Andrew.





More information about the Python-list mailing list