[Python-ideas] Extend the os.stat() result objects with methods like isfile() and isdir()

Pieter Nagel pieter at nagel.co.za
Thu May 2 18:49:50 CEST 2013


I propose adding methods like isfile(), isdir(), islink(), isfifo() and
so on - basically everything that would currently be done via code like
"stat.S_ISREG(s.st_mode)".

Please indicate support or not, so I can know whether to draft a PEP and
work on implementation.

My motivation is twofold:

Firstly, it would make code that needs to interpret stat() results using
the existing S_ISREG etc. methods in the stat module look cleaner, more
Pythonic, and less like C code manipulating bitmasks.

Secondly, in a recent discussion on python-dev [1] the issue was raised
that the stat() call can perform badly under certain situations, and
that some form of caching of the result of stat() calls is therefore
desirable.

This proposal makes it easier to do one form of caching stat() results:
the kind where the result is manually cached by storing it in some
variable.

Think of code such as:

  if os.path.isfile(f) or os.path.isdir(f):
    # do something

This will indirectly cause two calls to stat().

Currently, if you want to manually cache that stat call, you'll need to
write:

  s = os.stat(f)
  if stat.S_ISREG(s.st_mode) or stat.S_ISDIR(s.st_mode):
    # do something

This not only looks more convoluted and requires an extra import of
stat, but it also looks wildly different from the previous code even
though it basically has the same semantics.

Under my proposal, this could become:

  s = os.stat(f)
  if s.isfile() or s.isdir():
    # do something

This proposal is independent of the current PEP 428 Path object
proposal. However, if accepted, users of PEP 428 Path objects will also
benefit, since those can also return results of stat() calls.


-- 
Pieter Nagel





More information about the Python-ideas mailing list