[Tutor] Confused "from module import Name" better than "import module"?

Mike Hansen mhansen at cso.atmel.com
Mon Jul 11 21:04:21 CEST 2005


> Subject:
> Re: [Tutor] Confused "from module import Name" better than "import module"?
> From:
> Kent Johnson <kent37 at tds.net>
> Date:
> Mon, 11 Jul 2005 12:30:16 -0400
> 
> CC:
> tutor at python.org
> 
> 
> Mike Hansen wrote:
> 
>> I'm confused. I was just reading the URL below..
>>
>> http://jaynes.colorado.edu/PythonGuidelines.html
>>
>> and this statement confused me: "Always use from module import Name, 
>> Name2, Name3.. syntax instead of import module or from module import 
>> *. This is more efficient, reduces typing in the rest of the code, and 
>> it makes it much easier to see name collisions and to replace 
>> implementations."
>>
>> To me, import module is more explicit.
>> It seems to easier to read CoolModule.niceFunction() than just 
>> niceFunction(). You know exactly where niceFunction comes from 
>> especially when you've imported many modules. Don't you avoid 
>> namespace pollution too by using import module instead of from module 
>> import * or from module import Name, Name2, Name3...?
> 
> 
> from module import * is problematic and discouraged. It causes namespace 
> pollution and makes it harder to find out where a name is defined.
> 
> Other than that I think it is personal preference.
> 
> I often use from module import name because it reduces typing at the 
> point of use. It is still easy to find out where a name comes from by 
> searching for the name in the module. This adds a few names to the 
> global namespace but it is just the ones you use, nothing like what you 
> can get with from module import *.
> 
> I'm not sure what efficiency he is talking about - it might be faster to 
> look up a global name than to look up a name in a module but I would 
> want to test that. Anyway it is clearly a premature optimization and if 
> you have code where the cost of name lookup is hurting you then you will 
> want to convert the name to a local name, not a global.
> 
> I guess it could be easier to replace the implementation, for example if 
> you split a module you could change
> from module import Name1, Name1
> to
> from module1 import Name1
> from module2 import Name2
> and the rest of the client code wouldn't have to change.
> 
> my two cents
> Kent
> 

It's interesting. I still like the more explicit import Module. Even if you 
split the module, it wouldn't be hard to replace all occurrences of 
module1.sillyfunction with module2.sillyfunction. I'm sure vim and emacs can do 
this even across multiple files.

I suppose if you were only interested in one specific function from a module 
that you'd use from module import Name1.

Like you said, it's personal preference.

Thanks,

Mike


More information about the Tutor mailing list