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

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed.

5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I

6

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").

1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction).

6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it'

1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with.

3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you reall

1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

1

Many languages have a for-each loop.

4

When the first betas for Swift came out, I was impressed by their collection design. In particular, the way it allows them to write map-style functions that are lazy (like Python 3), but still as full-featured as possible.

2

In a previous post, I explained in detail how lookup works in Python.

2

The documentation does a great job explaining how things normally get looked up, and how you can hook them.

But to understand how the hooking works, you need to go under the covers to see how that normal lookup actually happens.

When I say "Python" below, I'm mostly talking about CPython 3.5.

7

In Python (I'm mostly talking about CPython here, but other implementations do similar things), when you write the following:

def spam(x): return x+1 spam(3) What happens?

Really, it's not that complicated, but there's no documentation anywhere that puts it all together.

2

I've seen a number of people ask why, if you can have arbitrary-sized integers that do everything exactly, you can't do the same thing with floats, avoiding all the rounding problems that they keep running into.

2

In a recent thread on python-ideas, Stephan Sahm suggested, in effect, changing the method resolution order (MRO) from C3-linearization to a simple depth-first search a la old-school Python or C++.

1

Note: This post doesn't talk about Python that much, except as a point of comparison for JavaScript.

Most object-oriented languages out there, including Python, are class-based. But JavaScript is instead prototype-based.

1

About a year and a half ago, I wrote a blog post on the idea of adding pattern matching to Python.

I finally got around to playing with Scala semi-seriously, and I realized that they pretty much solved the same problem, in a pretty similar way to my straw man proposal, and it works great.

About a year ago, Jules Jacobs wrote a series (part 1 and part 2, with part 3 still forthcoming) on the best collections library design.

1

In three separate discussions on the Python mailing lists this month, people have objected to some design because it leaks something into the enclosing scope. But "leaks into the enclosing scope" isn't a real problem.

2

There's a lot of confusion about what the various kinds of things you can iterate over in Python. I'll attempt to collect definitions for all of the relevant terms, and provide examples, here, so I don't have to go over the same discussions in the same circles every time.

8

Python has a whole hierarchy of collection-related abstract types, described in the collections.abc module in the standard library. But there are two key, prototypical kinds. Iterators are one-shot, used for a single forward traversal, and usually lazy, generating each value on the fly as requested.

2

There are a lot of novice questions on optimizing NumPy code on StackOverflow, that make a lot of the same mistakes. I'll try to cover them all here.

What does NumPy speed up?

Let's look at some Python code that does some computation element-wise on two lists of lists.

2

When asyncio was first proposed, many people (not so much on python-ideas, where Guido first suggested it, but on external blogs) had the same reaction: Doing the core reactor loop in Python is going to be way too slow. Something based on libev, like gevent, is inherently going to be much faster.

Let's say you have a good idea for a change to Python.

1

There are hundreds of questions on StackOverflow that all ask variations of the same thing. Paraphrasing:

lst is a list of strings and numbers. I want to convert the numbers to int but leave the strings alone.

2

In Haskell, you can section infix operators. This is a simple form of partial evaluation. Using Python syntax, the following are equivalent:

(2*) lambda x: 2*x (*2) lambda x: x*2 (*) lambda x, y: x*y So, can we do the same in Python?

Grammar

The first form, (2*), is unambiguous.

1

Many people—especially people coming from Java—think that using try/except is "inelegant", or "inefficient". Or, slightly less meaninglessly, they think that "exceptions should only be for errors, not for normal flow control".

These people are not going to be happy with Python.

2

If you look at Python tutorials and sample code, proposals for new language features, blogs like this one, talks at PyCon, etc., you'll see spam, eggs, gouda, etc. all over the place.

Most control structures in most most programming languages, including Python, are subordinating conjunctions, like "if", "while", and "except", although "with" is a preposition, and "for" is a preposition used strangely (although not as strangely as in C…).

There are two ways that some Python programmers overuse lambda. Doing this almost always mkes your code less readable, and for no corresponding benefit.

1

Some languages have a very strong idiomatic style—in Python, Haskell, or Swift, the same code by two different programmers is likely to look a lot more similar than in Perl, Lisp, or C++.

There's an advantage to this—and, in particular, an advantage to you sticking to those idioms.

1

Python doesn't have a way to clone generators.

At least for a lot of simple cases, however, it's pretty obvious what cloning them should do, and being able to do so would be handy. But for a lot of other cases, it's not at all obvious.

5

Every time someone has a good idea, they believe it should be in the stdlib. After all, it's useful to many people, and what's the harm? But of course there is a harm.

3

This confuses every Python developer the first time they see it—even if they're pretty experienced by the time they see it:

>>> t = ([], []) >>> t[0] += [1] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <stdin> in <module>()

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