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

MRAB python at mrabarnett.plus.com
Fri May 3 03:56:56 CEST 2013


On 03/05/2013 01:09, Andrew Barnert wrote:
> From: Christian Heimes <christian at python.org>
>
> Sent: Thursday, May 2, 2013 4:48 PM
>
>
>> Am 02.05.2013 18:49, schrieb Pieter Nagel:
>>>  Under my proposal, this could become:
>>>
>>>    s = os.stat(f)
>>>    if s.isfile() or s.isdir():
>>>      # do something
>
>
> +1
>
>> 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?
>
>
> Well, there's the fact that os.path.isfile is a callable.
>
True.

> And I've actually seen code that uses isfile in a filter call, and operator.attrgettr('is_file') obviously isn't as nice. But then a genexp is probably nicer than filter here anyway.
>
> So, two very trivial downsides. I guess +0.
>
>> 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()
>
> If this is _in addition to_ the methods/attributes, +1.
>
> If it's in place of them, -1. There are cases where this will be simpler, but for the most common case, s.isdir is much nicer than s.file_type == 'dir'.
>
>> 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.
>
>
> This one's actually a problem.
>
> If os.path.isfile(name) is true, and so is s.isfile, but s.file_type=='file' is false, that's going to be confusing. Especially to novices and Windows programmers—the very people who write code like os.path.islink(f) or os.path.isdir(x) today because they're afraid of the stat module, who we're trying to help here. In fact, I suspect that, even after they learn that it's "reg" rather than "file", they're going to have a hard time remembering it.
>
It wouldn't be """s.file_type=='file'""", but """'file' in s.file_type""".

And I agree about 'reg'.

> But calling it 'file' is confusing to everyone who _does_ know stat. Anything you can call stat on is a file.
>
...even if os.path.isfile(...) says it isn't.

> And I don't know of a good answer here.
>
Maybe "file_type" is the wrong name for it.




More information about the Python-ideas mailing list