Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap"). In Java or C#, you need "interfaces" all over the place; you can't pass something to a function unless it's an instance of a type that implements that interface; in Python, as long as your object has the methods and other attributes that the function needs, no matter what type it is, everything is good.

Of course there are some occasions where you do need to LBYL. For example, say you need to do a whole set of operations or none at all. If the second one raises a TypeError after the first one succeeded, now you're in an inconsistent state. If you can make the first operation reversible—or, better, do the whole transaction on a copy of your state, off to the side, and then commit it atomically at the end—that may be acceptable, but if not, what can you do? You have to LBYL all of the operations before you do the first one. (Of course if you have to worry about concurrency or reentrancy, even that isn't sufficient—but it's still necessary.)

hasattr

Traditionally, in Python, you handled LBYL by still using duck-typing: just use hasattr to check for the methods you want. But this has a few problems.

First, not all distinctions are actually testable with hasattr. For example, often, you want a list-like object, and a dict-like object won't do. But you can't distinguish with __getitem__, because they both support that. You can try to pile on tests--has __getitem__, and __len__, but doesn't have keys... But that's still going to have false positives once you go beyond the builtin types, and it's hard to document for the user of your function what you're testing for, and you have to copy and paste those checks all over the place (and, if you discover that you need to add another one, make sure to update all the copies). And remember to test according to special-method lookup (do the hasattr on the type, not the object itself) when appropriate, if you can figure out when it is appropriate.

And, on top of the false positives, you may also get false negatives--a type that doesn't have __iter__ may still work in a for loop because of the old-style sequence protocol. So, you have to test for having __iter__ or having __getitem__ (but then you get back to the false positives). And, again, you have to do this all over the place.

Finally, it isn't always clear from the test what you're trying to do. Any reader should understand that a test for __iter__ is checking whether an object is iterable, but what is a test for read or draw checking?

The obvious way to solve these problems is to factor out an issequence function, an isiterable function, and so on.

ABCs

ABCs ("Abstract Base Classes") are a way to make those functions extensible. You write isinstance(seq, Sequence) instead of issequence(seq), but now a single builtin function works for an unbounded number of interfaces, rather than a handful of hardcoded ones. And we have that Sequence type to add extra things to. And there are three ways to hook the test.

First, similar to Java interfaces, you can always just inherit from the ABC. If you write a class that uses Sequence as a base class, then of course isinstance(myseq, Sequence) will pass. And Sequence can use abstractmethod to require subclasses to implement some required methods or the inheritance will fail.

Alternatively, similar to Go interfaces, an ABC can include structural tests (in a __subclasshook__ method) that will automatically treat any matching type as a subclass. For example, if your class defines an __iter__ method, it automatically counts as a subclass of Iterable.

Finally, you can explicitly register any type as a virtual subclass of an ABC by calling the register method. For example, tuple doesn't inherit from Sequence, and Sequence doesn't do structural checking, but because the module calls Sequence.register(tuple) at import time, tuples count as sequences.

Most OO languages provide either the first option or the second one, which can be a pain. In languages with only nominal (subclass-based) interfaces, there's no way to define a new interface like Reversible that stdlib types, third-party types, or even builtins like arrays can match (except n a language like like Ruby, where you can always reopen the classes and monkeypatch the inheritance chain at runtime, and it's even idiomatic to do so.) In languages with only structural interfaces, there's no way to do things like specify sequences and mappings as distinct interfaces that use the same method names with different meanings. (That's maybe not s much of a problem for named methods, but think about operator overloading and other magic methods—would you really want to spell dict access d{2} or similar instead of d[2] just so sequences and mappings can use different operators?)

Sometimes, ABCs can clarify an interface even if you don't actually use them. For example, Python 2 made heavy use of the idea of "file-like objects", without ever really defining what that means. A file is an iterable of lines; an object with read() to read the whole thing and read(4096) to read one buffer; an object with fileno() to get the underlying file descriptor to pass to some wrapped-up C library; and various other things (especially once you consider that files are also writable). When a function needs a file-like object, which of these does it need? When a function gives you a file-like object, which one is it providing? Worse, even actual file objects come in two flavors, bytes and Unicode; an iterable of Unicode strings is a file-like object, but it's still useless to a function that needs bytes.

So, in Python 3, we have RawIOBase and TextIOBase, which specify exactly which methods they provide, and whether those methods deal in bytes or text. You almost never actually test for them with isinstance, but they still serve as great documentation for both users and implementers of file-like objects

But keep in mind that you don't want to create an ABC in Python whenever you'd create an interface in Java or Go. The vast majority of the time, you want to use EAFP duck typing. There's no benefit in using them when not required (Python doesn't do type-driven optimizations, etc.), and there can be a big cost (because so much Python code is written around duck-typing idioms, so you don't want to fight them). The only time to use ABCs is when you really do need to check that an object meets some interface (as in the example at the top).

ABCs as mixins

The obvious problem with the more complex ABCs is that interfaces like Sequence or RawIOBase have tons of methods. In the Python 2 days, you'd just implement the one or two methods that were actually needed (once you guessing which ones those were) and you were done.

That's where mixins come in. Since ABCs are just classes, and mixins are just classes, there's nothing stopping an ABC from providing default implementations for all kinds of methods based on the subclass's implementations of a few required methods.

If you inherit from Sequence, you only have to implement __getitem__ and __len__, and the ABC fills in all the rest of the methods for you. You can override them if you want (e.g., if you can provide a more efficient implementation for __contains__ than iterating the whole sequence), but you usually don't need to. A complete Sequence is under 10 lines of code for the author, but provides the entire interface of tuple for the user.

Of course there are other ways Python could provide similar convenience besides mixins (e.g., see functools.total_ordering, a decorator that similarly lets you define just two methods and get a complete suite implemented for you), but mixins work great for this case.

Isn't it conceptually wrong for an interface (which you inherit for subtyping) and a mixin (which you inherit for implementation) to be the same class? Well, it's not exactly "pure OO", but then practicality beats purity. Sure, Python could have a SequenceABC and a SequenceMixin and make you inherit both separately when you want both, but when are you going to want SequenceMixin without also wanting SequenceABC? Merging them is very often helpful, and almost never a problem.
1

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.