Marc Tompkins wrote:
On Sun, Nov 15, 2009 at 4:11 PM, Stephen Nelson-Smith <sanel...@gmail.com>wrote:

import gzip
from heapq import heappush, heappop, merge
Is this a preferred method, rather than just 'import heapq'?

It has a couple of advantages:
-  convenience: if you "import heapq", then to do a push you need to type
"heapq.heappush"; if you do "from heapq import heappush", then you can
simply type "heappush" to use it.
-  efficiency: you import only what you actually need to use.  Importing all
from xx import yy, zz gets the whole module xx, not just the functions yy and zz. It just doesn't add the module name to the present global namespace. That changes the way you reference yy and zz, but it doesn't decrease the load time or the memory used. And if you want to cheat, you can reference the rest of the module with something like:
   sys.modules["heapq"].heapify()

or even
heapq = sys.modules["heapq"]

which then gets you where you would have been had you just imported the module the first place.
of a gigantic package to use one or two methods is wasteful; on the other
hand, if a package contains five methods and you're using four of them, this
might not be such a big deal.
Now you switch from talking about modules (heapq) to packages. I don't believe packages are loaded monolithically, but just modules.
Remember, this is Python... there's always going to be more than one way to
do it, and you'll get an argument on this list for every one of them.

What you should NEVER do, though: "from package import *"
Definite agreement on that one.

Consider the following two lines:

from hashlib import md5
q3 = sys.modules["hashlib"].sha1

Without the first line, the second one gets an error. So the import is indeed getting more than just the md5 constructor.


DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to