By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,985 Members | 1,574 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,985 IT Pros & Developers. It's quick & easy.

Questions about the import ordering

ChrisWang
P: 9
Dear all,

I am reading the book "Core Python Programming". In the chapter talking about modules, it says the modules should follow this ordering:

Expand|Select|Wrap|Line Numbers
  1. import Python Standard Library modules
  2.  
  3. import Python third party modules
  4.  
  5. import Application-specific modules
I am not sure whether the ordering will impact the module's loading or search efficiency. For example, a common module in the standard library can be free from being imported several times, if this module will be imported by application-specific modules.

test.py
Expand|Select|Wrap|Line Numbers
  1. #test.py
  2. import os
  3. import MyModuleA
  4. import MyModuleB
  5. ...
  6.  
MyModuleA.py
Expand|Select|Wrap|Line Numbers
  1. #MyModuleA.py
  2. import os
  3. ...
  4.  
MyModuleB.py
Expand|Select|Wrap|Line Numbers
  1. #MyModuleB.py
  2. import os
  3. ...
  4.  
If we follow the ordering to import the modules, here we import standard library "os", we may save some time, right? It's only my assumption and I am not sure I am right. But I am curious to know whether there are some benefits we can get from the this ordering.

Could anyone be kind enough to give me the answer? Thanks a lot.

Have a nice holiday!
Dec 18 '08 #1
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
A module is imported and executed only once. A subsequent import of the same module only creates a reference to the module namespace created on the previous import.

The ordering of the imports is primarily for consistency and is recommended in PEP 8. I don't know if there are any performance benefits.

-BV
Dec 18 '08 #2

ChrisWang
P: 9
@bvdet
Thanks BV. Could you please show me detailed explanation about the consistency?
I've read the description about imports in PEP08, but I think I am still puzzled about that.
Dec 18 '08 #3

bvdet
Expert Mod 2.5K+
P: 2,851
ChrisWang,

Sorry, I have no detailed explanation. I think the reference to consistency is referring to Python applications in general.

If a top level module imports a required Python library module and another application specific module is imported and executed and it imports the same Python library module, a reference is made to the module instead of it being importing again. If you think about it, it makes sense to order the imports that way.

I would not import a module unless the current module requires it.

-BV
Dec 19 '08 #4

ChrisWang
P: 9
Ok. Thank you very much.

Have a great holiday!
Dec 22 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.