Thanks to visit codestin.com
Credit goes to github.com

Skip to content

os.lstat() supports dir_fd but is not in os.supports_dir_fd #134993

Closed
@tormol

Description

@tormol

Bug report

Bug description:

I had written a script using os.fwalk() and os.lstat(), which was working.
Then I added an if os.lstat in os.supports_dir_fd check and a fallback implementation and observed the fallback path being taken:

import os, sys
from datetime import datetime

oldest = datetime.max
newest = datetime.min
oldest_file = None
newest_file = None

if os.lstat in os.supports_dir_fd:
    for dir, _, files, dirfd in os.fwalk(sys.argv[1]):
        for file in files:
            mtime = os.lstat(file, dir_fd=dirfd).st_mtime
            date = datetime.fromtimestamp(mtime)
            if date < oldest:
                oldest = date
                oldest_file = os.path.join(dir, file)
            if date > newest:
                newest = date
                newest_file = os.path.join(dir, file)
else:
    print('not using dir_fd')
    # for dir, _, files in os.walk(sys.argv[1], followlinks=False): ...

print('Newest:', newest.strftime('%Y-%m-%d %H-%M-%S'), newest_file)
print('Oldest:', oldest.strftime('%Y-%m-%d %H-%M-%S'), oldest_file)

The workaround is to check for os.stat instead (and use os.stat(..., follow_symlinks=False) for consistency).

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions