On 1/9/2017 6:42 AM, 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?

If the module does not define __all__, it prevents * imports of the module from also importing the imported modules. For instance:

>>> sys
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    sys
NameError: name 'sys' is not defined
>>> from tkinter import *
>>> sys
<module 'sys' (built-in)>
>>> enum
<module 'enum' from 'C:\\Programs\\Python36\\lib\\enum.py'>
>>> itertools
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    itertools
NameError: name 'itertools' is not defined

Use of such undocumented and unintended attributes of a module is fragile.

1. The imported module could be changed. Tkinter's 'import enum' in only used in "class EventType(str, enum.Enum):". The import could well be changed to 'from enum import Enum' or even better, 'from enum import Enum as _Enum' and the one use modified.

2. The importing module could be changed. 'from tkinter import *' might be changed to 'from tkinter import tk, ...' or 'import tkinter as tk' or even replaced by another module.

--
Terry Jan Reedy

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to