[Python-Dev] Imports with underscores

André Malo nd at perlig.de
Mon Jan 9 12:23:58 EST 2017


* Steve Holden 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?

For me (in favor of underscored imports), the following items apply:

- the imports are usually not part of the exported API. (If they are, I 
  specifically do not underscore them)

- __all__ was referenced in other answers. However, it only protects from a 
  single use case (import *). It does not help you directly with shells 
  (dir(), ipython tab expansion (?)) and it's easy to ignore if you look at 
  the source code itself (because, let's face it, documentation often 
  sucks).

- __all__ again: it's tedious and error-prone to maintain. I often found
  places in my own code where it was plain wrong. (pylint helps these days 
  against wrongness, but not against incompleteness)

- In my code (inside the module): I usually know exactly what 
  variable is a module and what is not (by the underscores)

- Also in my code - from time to time the modules steal good names for local 
  variables, underscoring also solved this problem for me.

Cheers,
nd
-- 
die (eval q-qq:Just Another Perl Hacker
:-)

# André Malo, <http://pub.perlig.de/> #


More information about the Python-Dev mailing list