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

David Mertz mertz at gnosis.cx
Thu May 2 20:14:37 CEST 2013


+1
On May 2, 2013 11:13 AM, "MRAB" <python at mrabarnett.plus.com> wrote:

> On 02/05/2013 17:49, Pieter Nagel wrote:
>
>> 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.
>>
>>
>>  +1
>
> It also means not having to import the stat module to get the
> strangely-named (to me) constants (why the "S_" prefix? Yes, I do know
> why, BTW. :-)).
>
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130502/6ffe221e/attachment.html>


More information about the Python-ideas mailing list