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

Christian Heimes christian at python.org
Fri May 3 01:48:18 CEST 2013


Am 02.05.2013 18:49, schrieb Pieter Nagel:
> 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.

Hi Pieter,

I like your proposal. We could take the opportunity now and push the
proposal one or two steps further.


First step: drop the function call

stat_result.isfile() or stat_result.isdir() don't have to be functions.
The feature can also be implemented with properties, e.g.
stat_result.is_file. Or can somebody think of a reason why they have to
be callables anymore?


Second step: get file type as string

A property stat_result.file_type that returns the type of the file as
string makes checks like "s.is_dir or s.is_file" even easier:

s = os.stat(f)
if s.file_type in {'reg', 'dir'}:
   do_something()

We have to agree on a set of names, though. IMHO the abbreviations from
stat.h are clear and distinct: {'fifo', 'chr', 'dir', 'blk', 'reg',
'lnk', 'sock', 'door', 'port'}. door and port are special file types on
Solaris.

Christian



More information about the Python-ideas mailing list