Efficiency/style issues of import <module> vs. from <module> import <name>, ...

Jack Diederich jackdied at gmail.com
Thu Jun 17 13:22:21 EDT 2010


On Thu, Jun 17, 2010 at 12:58 PM, Stephen Hansen
<me+list/python at ixokai.io> wrote:
> On 6/17/10 10:01 AM, Ethan Furman wrote:
>> Stephen Hansen wrote:
>>> On 6/17/10 9:12 AM, python at bdurham.com wrote:
>>>
>>> Now, this is all IMHO: the style guide does not define any 'guidelines'
>>> on this, except that its okay to use "from ... import ..." to pull in
>>> classes and (implicitly) constants, and despite how the rules say 'one
>>> module per line' its OK to pull in more then one name -from- a module at
>>> once.
>>
>> What do you mean by "(implicitly) constants"?
>
> Quote, PEP-8:
>
>  - Imports should usually be on separate lines, e.g.:
>
>        Yes: import os
>             import sys
>
>        No:  import sys, os
>
>      it's okay to say this though:
>
>        from subprocess import Popen, PIPE
>
> It explicitly states later its entirely OK to import classes. It never
> says anything else directly, except in the example given, it shows you
> importing a constant. So, its giving implicit approval to that without
> really directly saying anything about it.

You want to import a name that is itself a namespace; preferably a
module or package and sometimes a class.  Importing constants can lead
to trouble.  ex/

from settings import DEBUG
if DEBUG: log('debug is on!')

The value of the flag gets fetched at import time.  If code in another
module updates settings.DEBUG later your module won't see it. ditto
for exceptions.

-Jack



More information about the Python-list mailing list