Speed ain't bad
Jeff Shannon
jeff at ccvcorp.com
Mon Jan 3 14:35:56 EST 2005
Anders J. Munch wrote:
> Another way is the strategy of "it's easier to ask forgiveness than to
> ask permission".
> If you replace:
> if(not os.path.isdir(zfdir)):
> os.makedirs(zfdir)
> with:
> try:
> os.makedirs(zfdir)
> except EnvironmentError:
> pass
>
> then not only will your script become a micron more robust, but
> assuming zfdir typically does not exist, you will have saved the call
> to os.path.isdir.
... at the cost of an exception frame setup and an incomplete call to
os.makedirs(). It's an open question whether the exception setup and
recovery take less time than the call to isdir(), though I'd expect
probably not. The exception route definitely makes more sense if the
makedirs() call is likely to succeed; if it's likely to fail, then
things are murkier.
Since isdir() *is* a disk i/o operation, then in this case the
exception route is probably preferable anyhow. In either case, one
must touch the disk; in the exception case, there will only ever be
one disk access (which either succeeds or fails), while in the other
case, there may be two disk accesses. However, if it wasn't for the
extra disk i/o operation, then the 'if ...' might be slightly faster,
even though the exception-based route is more Pythonic.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list