Why "flat is better than nested"?

Alex Willmer alex at moreati.org.uk
Mon Oct 25 09:34:10 EDT 2010


On Oct 25, 11:07 am, kj <no.em... at please.post> wrote:
> In "The Zen of Python", one of the "maxims" is "flat is better than
> nested"?  Why?  Can anyone give me a concrete example that illustrates
> this point?

I take this as a reference to the layout of the Python standard
library and other packages i.e. it's better to have a module hierarchy
of depth 1 or 2 and many top level items, than a depth of 5+ and only
a few top level items.

For instance

import re2
import sqlite3
import logging

import something_thirdparty

vs

import java.util.regex
import java.sql
import java.util.logging

import org.example.thirdparty.something

There are of course some Python packages that go deeper than 2
(xml.dom.minidom), but the majority are shallow. I think the
motivation is to make the packages more discoverable, and to avoid
classification arguments (does regex go under util or text). Alone the
statement would imply a single, global space ala C but that of course
is evil and so one must balance it with "Namespaces are one honking
great idea -- let's do more of those!"

I don't think it applies to data structures though. If a deeply nested
tree models your data well, then use it.

Regards, Alex



More information about the Python-list mailing list