Why are python imports renamed with leading underscores

Viewed 1827

I noticed it at work with functools.partial and also in python source code itself. E.g. below from collections.py

from operator import itemgetter as _itemgetter, eq as _eq
from keyword import iskeyword as _iskeyword
import sys as _sys
import heapq as _heapq

What is the rationale for doing so? If this was C++ I understand it could cause namespace conflicts however in python wouldn't these names be local to the module in which they are imported? Unless someone does import *, but that's discouraged so I'm not sure that's the reason.

1 Answers

This indicates that the function, variable or class is private. Not only is it a human convention (so you should know not to use it), but python also enforces that it will not be imported in certain conditions.

From PEP8:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

PS: Using import * is not good practice, but that's another discussion.

Related