Skip to content

[aiofiles] .name on NamedTempFile is always a str #13621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions stubs/aiofiles/aiofiles/threadpool/text.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from _typeshed import FileDescriptorOrPath
from collections.abc import Iterable
from typing import BinaryIO

Expand Down Expand Up @@ -34,7 +33,7 @@ class _UnknownAsyncTextIO(AsyncBase[str]):
@property
def newlines(self) -> str | tuple[str, ...] | None: ...
@property
def name(self) -> FileDescriptorOrPath: ...
def name(self) -> str: ...
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we can do this unconditionally. aiofiles.threadpool.open() will also return an AsyncTextIOWrapper, which might be a file descriptor:

import asyncio
from os import fdopen

from aiofiles import open as aioopen

async def main():
    f = open("bar.txt")
    async with aioopen(f.fileno()) as aiof:
        print(type(aiof.name))  # <class 'int'>

asyncio.run(main())

Maybe it's best if we make _UnknownAsyncTextIO and the two wrapper classes generic over name with a default of FileDescriptorOrPath. Then we can bind this to str in the return type of NamedTemporaryFile.

In fact, we could use this as a template for the stdlib, where we already have a comment alluding to this:

typeshed/stdlib/typing.pyi

Lines 771 to 774 in 0b8dcfc

# Usually str, but may be bytes if a bytes path was passed to open(). See #10737.
# If PEP 696 becomes available, we may want to use a defaulted TypeVar here.
@property
def name(self) -> str | Any: ...

Copy link
Member Author

@sobolevn sobolevn Mar 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea! Thanks a lot! ❤️

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now, when I double checked that, I think that I would prefer to close this PR, because it is too complex. Notice that def NamedTemporaryFile has multiple @overloads that return different subtypes of _UnknownAsyncBinaryIO, not even direct ones. I think that making all of the generic is an overkill :(

@property
def mode(self) -> str: ...

Expand Down