simple Thread question

Peter Hansen peter at
Wed Aug 18 04:20:01 CEST 2004

Beeyah wrote:

> adeger at (adeger) wrote in message news:<b8001e9f.0408031151.4f617c6 at>...
>>	def run(self, name):
>>		import time
>>		for i in range(1,11):
>>			print 'thread ', name, ' instance ', str(i)
>>			time.sleep(1)
> You're importing the time module for every TestThr() object you
> create, that's no good. You only need to import the module once, at
> the beginning of the file like you've done with threading.

While it's true that that is all that's needed, it is not
required, and doesn't really provide any performance
improvements.  I often do the above sort of thing where I
use a given module in only one place, especially when using
threads where it feels subtly cleaner to defer loading of
some modules until the thread actually starts.

Modules are really ever imported only once and after that
the "import" statement amounts to retrieving a reference
by looking it up in the sys.modules dictionary.  In the
case of a builtin module like "time", there isn't even
any significant overhead involved in the first import,
as there might be with a .py module (where the timestamp
encoded in the .pyc file is compared with the timestamp
of the .py file, and the .py file is recompiled if
necessary, and then a new module object is created and
the bytecode is executed in its namespace, etc).


More information about the Python-list mailing list