Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are modules imported as _<name> in another module?

There are several cases in the Python standard library where modules are imported with a leading underscore (_) in their name. I wonder why this is necessary, as it is under the module's name anyways and from ... import * will respect the __all__ variable for what to import.

Does anyone know why this is used/necessary?

An example is argparse which has the following imports:

import collections as _collections
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
like image 239
kiri Avatar asked Dec 24 '13 08:12

kiri


2 Answers

In Python a single leading underscore means "this is an implementation detail, not part of the API".

The point here is to make clear that the importing module (argparse in your example) uses the imported one but does not expose them as part of it's own API - ie, you (as a client of the API) should not rely on argparse.collections being available - if you want collections, you have to import it explicitly.

like image 191
bruno desthuilliers Avatar answered Oct 23 '22 18:10

bruno desthuilliers


To expand on arun's answer...

The reasoning presented in https://mail.python.org/pipermail/python-dev/2013-July/127286.html is that names prefixed with underscores are classed as "internal implementation" and no future guarantees of backwards compatibility are made. That means that is you even find yourself using thing._otherThing you know you are on shaky grounds, comes future updates.

This means that these modules takes care to explicitly point out that you should not rely on what they import, as that is merely an internal implementation detail.

like image 32
Vatine Avatar answered Oct 23 '22 19:10

Vatine