Lack of each form
When reading the code of other people (and these people use very different import styles), I noticed the following problems with each of the styles:
import modulewithaverylongname will clutter the code further down with a long module name (for example, concurrent.futures or django.contrib.auth.backends ) and a decrease in readability in these places.
from module import * does not allow me to syntactically see that, for example, classA and classB come from the same module and have much in common with each other. This makes code reading tough. (This name from such an import is possible; shadow names from an earlier import are the smallest part of this problem.)
from module import classA, classB, functionC, constantD, functionE overloads my short-term memory with too many names that I mentally have to assign module to coordinate the code.
import modulewithaverylongname as mwvln sometimes not enough mnemonic for me.
Suitable compromise
Based on the above observations, I developed the following style in my own code:
import module is the preferred style if the module name is short such as most packages in the standard library. This is also the preferred style if I need to use names from a module in only two or three places in my own module; ( "Readability metrics" ).
import longername as ln is the preferred style in almost every other case. For example, I could import django.contrib.auth.backends as dj_abe . By the definition of the above criterion 1, the abbreviation will be used often and therefore easy to remember.
Only these two styles are completely pythonic according to "Explicit rule is better than implicit." .
from module import xx still occurs sometimes in my code. I use it in cases where even the as format looks exaggerated, the most famous example is from datetime import datetime .
Lutz Prechelt Mar 22 '15 at 11:24 2015-03-22 11:24
source share