[Python-Dev] Imports with underscores

Paul Moore p.f.moore at gmail.com
Mon Jan 9 11:31:46 EST 2017


On 9 January 2017 at 11:42, Steve Holden <steve at holdenweb.com> wrote:
> One of my developers recently submitted a pull request incuding a number of
> lines like
>
> import os as _os
>
> When I asked him why he suggested a) this would improve encapsulation, and
> b) the practice was supported in the stdlib. Further investigation reveals
> that some modules (e.g. argparse, crypt, difflib, random) do use this
> technique, but it is far from universal.
>
> So I thought it would be useful to get input from current devs about the
> value of this practice, since to me it seems somewhat anti-pythonic. What
> advantages does it confer?

As I understand it, it prevents the imports showing up in "import *"
imports, but using __all__ is better. I'd imagine usage in the stdlib
is mainly historical.

It's not a practice I'd recommend in user code. The needs of the
stdlib are somewhat special (and stdlib code can be many years old,
reflecting out of date design rules) and "because the stdlib does it"
is not necessarily a compelling argument in the absence of an actual
justification.

Regarding "improves encapsulation", as Barry mentioned, using __all__
(and avoiding import-* anyway) is a better approach. Furthermore,
Python does not encourage strict (as in, enforced, encapsulation).
This is very much a "consenting adults" situation - by hiding imports
like this, you make it harder to monkeypatch (for testing purposes,
for example). Users are meant to stick to the published API of a
module *because it's the right thing to do*, not because they are
forced to.

Paul


More information about the Python-Dev mailing list