classification
Title: Inconsistent behavior: Get st_nlink from os.stat() and os.scandir()
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Mohanson Leaf, josh.r, paul.moore, steve.dower, tim.golden, vstinner, zach.ware
Priority: normal Keywords:

Created on 2016-09-09 09:24 by Mohanson Leaf, last changed 2017-04-21 23:46 by vstinner. This issue is now closed.

Files
File name Uploaded Description Edit
stat.py Mohanson Leaf, 2016-09-09 09:24 python3.5 stat.py
Pull Requests
URL Status Linked Edit
PR 795 closed mark.becwar, 2017-03-23 23:01
Messages (3)
msg275293 - (view) Author: Mohanson Leaf (Mohanson Leaf) Date: 2016-09-09 09:24
os.stat(file).st_nlink gives 1 but same file's st_nlink from os.scandir(dir) gives 0.


"""
Inconsistent behavior: Get st_nlink from os.stat() and os.scandir()
Platform: Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
"""

import os
import os.path

print('os.stat:', os.stat(__file__).st_nlink)

for entry in os.scandir(os.path.dirname(os.path.abspath(__file__))):
    if entry.name == 'stat.py':
        print('os.scandir:', entry.stat().st_nlink)

"""
os.stat: 1
os.scandir: 0
"""
msg290072 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2017-03-24 00:58
This is documented behavior. Per the docs for os.DirEntry's stat method (the objects yielded by os.scandir):

>On Windows, the st_ino, st_dev and st_nlink attributes of the stat_result are always set to zero. Call os.stat() to get these attributes.

It might be nice if those values could be cached on read (through a lazily initialized value on property access or the like), but this is not a bug, it's working as documented.
msg292085 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2017-04-21 23:46
scandir () is designed for effiency, not for portability or correctness. The API has deliberate limitations which are well documented, as the one you spotted:
https://docs.python.org/dev/library/os.html#os.DirEntry.stat

Your PR would defeat the whole purpose of scandir.
History
Date User Action Args
2017-04-21 23:46:00vstinnersetstatus: open -> closed

nosy: + vstinner
messages: + msg292085

resolution: not a bug
stage: resolved
2017-03-24 00:58:30josh.rsetnosy: + josh.r
messages: + msg290072
2017-03-23 23:01:53mark.becwarsetpull_requests: + pull_request700
2016-09-09 09:24:54Mohanson Leafcreate