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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With