"from module import data; print(data)" vs "import module; print(module.data)"

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Thu Feb 25 15:00:49 EST 2016


On Wednesday, February 24, 2016 at 5:07:57 PM UTC-8, Dan Stromberg wrote:
> Could people please compare and contrast the two ways of doing imports
> in the Subject line?
> 
> I've long favored the latter, but I'm working in a code base that
> prefers the former.
> 
> Is it fair to say that the former increases the surface area of your
> shared (sometimes mutable) state?
> 
> It's clear that the former saves keystrokes.
> 
> I find the latter a little more clear, because you don't have to go
> look for where a symbol came from.
> 
> Anything else?
> 
> Thanks!

If I'm only importing a single class or function from a module AND that class or function has a very meaningful name, I will use "from MyModule import MyUsefulClass".  Otherwise, I just use "import MyModule".

Now, I've noticed people talking about importing os.path.  Is there any reason to use "import os.path" rather than "import os"?  Both of them will still put the "os" module into the global namespace.


More information about the Python-list mailing list