tempfile.NamedTemporaryFile wont work

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Nov 19 15:02:11 CET 2006


On Sun, 19 Nov 2006 13:18:39 +0100, Bjoern Schliessmann wrote:

> Imbaud Pierre wrote:
> 
>>              tf = tempfile.NamedTemporaryFile()
>>              tfName = tf.name
>> [...]
>>              print >> sys.stderr, '%s: %s' % (tfName, ['no',
>> 'yes'][os.path.exists(tfName)])
>>              subprocess.Popen(['strings', tfName])
> 
> Just out of curiosity: Why did you assign tf.name to tfname?
> 
> Hypothetically, if tf.name changed, tfname wouldn't follow since
> strings are immutable.

Well, yes, but if tf.name changed, that won't change the file name on disk
either:

>>> tf = tempfile.NamedTemporaryFile()
>>> tf.name
'/tmp/tmpYVV1Ij'
>>> os.path.exists(tf.name)
True
>>> oldname = tf.name
>>> tf.name = "/tmp/something"
>>> os.path.exists(tf.name)
False
>>> os.path.exists(oldname)
True


I'm guessing that binding tf.name to tfName is a micro-optimization. In a
very tight loop, name lookups can take considerable time, and one
optimization can be to reduce the number of lookups:

method = something.method
while 1:
    something.method # needs at least two lookups
    method # needs a single lookup


-- 
Steve.




More information about the Python-list mailing list