In Python, Is The Idiom "from Module Import Classname" Typical?
Solution 1:
To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide
it's okay to say this though:
from subprocess import Popen, PIPE
I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.
Eg suppose the module Thing
doesn't have a Thyng
member
fromThingimportThyng
Goes wrong immediately you run the .py
file, whereas
import Thing
# ...
def fn():
Thing.Thyng()
Doesn't go wrong until you run fn()
As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py
and implementation files. Importing things into the __init__.py
keeps the interface the same. It is common practice in the standard libraries too.
Solution 2:
Yes. Both are idiomatic Python in my opinion.
I tend to use the from module import name
form for some modules in the standard library, such as datetime
, but mostly for closely related modules, or names that are frequently used in the module. For example, I typically import ORM classes in this way.
I tend to use the import module
form for some standard modules (especially os
and os.path
) and for names that are not very distinctive (like database.session
and cherrypy.session
being two different kind of sessions) and for name that are used infrequently where the mention of the module name improves readability.
In the end, there are a few rules of thumb (such as import os.path
), but which form to use is largely a matter of judgement, taste and experience.
Solution 3:
To address if it is pythonic, take a look at what is generally the definitive answer on the internet: http://effbot.org/zone/import-confusion.htm
Also take a look at ~unutbu's link which discusses this in greater detail.
Solution 4:
I use from itertools import chain, ifilter, islice, izip
all the time, because it allows me to program as though those were built-in methods, which to my way of thinking they really ought to be.
Once, in a frenzy of misguided correctness, I went through a big block of code and replaced from datetime import datetime
with import datetime
. This was a good example of Mark Twain's observation that a man who picks up a rat by the tail learns something that can be learned no other way. It certainly set me straight on why it's OK to use from x import y
.
Post a Comment for "In Python, Is The Idiom "from Module Import Classname" Typical?"