Most efficient way to write data out to a text file?

Fredrik Lundh fredrik at
Sat Jun 29 15:05:18 EDT 2002

Dave Kuhlman wrote:

> > 1) "import sys" became "import exit from sys"
> > 2) "import os" became "import makedires from os"
> Does importing a function from a module (as opposed to importing
> the whole module) save a look-up each time the function is called?


but evaluating "exit" instead of "sys.exit" saves one lookup.

(the latter first looks up "sys" in the global namespace, and
then "exit" in the sys namespace).

(not that it matters for these functions; it didn't sound like
his performance problem was that Python couldn't exit fast
enough ;-)

> > 3) "import time" bacame "import asctime from time" (this one is
> > used frequently)

"from time import asctime", I hope.

> Is finding things in globals slower than finding them in locals?

yes.  Python assigns integer indices to local names, and
stores the corresponding objects in an array.

globals (and ordinary object attributes) are stored in a

if you read enough code, you'll find that "rebinding" is a pretty
common pydiom in performance-critical code.  some examples:

    import time

    def myfunction(...):

        # bind asctime to a local name
        asctime = time.asctime

        for ... in ...:
            x = asctime(...)

this also works for methods:

    def myotherfunction(...):
        result = []
        append = result.append
        for .. in ...:
            append(...) # appends to result
        return result

since arguments are also treated as local variables, and
default values are evaluated once (when the function
object is created), you'll also find things like:

    def myfunction(..., asctime=time.asctime):
        for ... in ...:
            x = asctime(...)

> Did this change in Python 2.2?



More information about the Python-list mailing list