Skip to content

Using os.PathLike as an annotation #5667

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

Closed
scolby33 opened this issue Sep 25, 2018 · 4 comments
Closed

Using os.PathLike as an annotation #5667

scolby33 opened this issue Sep 25, 2018 · 4 comments

Comments

@scolby33
Copy link

I am trying to create a typealias for all the types that can be passed as the first argument of open(). MyPy reveals the type to be Union[builtins.str, builtins.bytes, builtins.int, builtins._PathLike[Any]].

My first attempt at this is:

Openable = Union[str, bytes, int, os.PathLike[Any]]

MyPy is happy with this, but alas Python is not:

TypeError: 'ABCMeta' object is not subscriptable

Trying this, then:

Openable = Union[str, bytes, int, os.PathLike]

But now MyPy is unhappy:

error: Missing type parameters for generic type

What is the correct way of using os.PathLike here? There is no typing.PathLike yet. Do I have to create my own generic version of os.PathLike?

@msullivan
Copy link
Collaborator

I think the fix is to quote the type so that it is not evaluated at runtime:

Openable = Union[str, bytes, int, 'os.PathLike[Any]']

@ilevkivskyi
Copy link
Member

Another solution is to use if TYPE_CHECKING: ....

This problem appeared several times. It would be great to create a documentation entry about this.

@scolby33
Copy link
Author

scolby33 commented Oct 1, 2018

Oh of course, how could I have forgotten about the string version of annotations!?

+1 to a mention in documentation

@ilevkivskyi
Copy link
Member

Another example is when the class that is generic in typeshed is not generic at runtime appears as a base class. This case is even more important, since one can't use quotes and if TYPE_CHECKING: ... is the only way.

@ilevkivskyi ilevkivskyi self-assigned this Oct 24, 2018
sgbaird added a commit to sparks-baird/mat_discover that referenced this issue Feb 22, 2022
facebook-github-bot pushed a commit to mapillary/OpenSfM that referenced this issue Apr 6, 2022
Summary:
python/mypy#5667

python/typeshed#3202

Reviewed By: fabianschenk

Differential Revision: D35423993

fbshipit-source-id: 73e2027ea425eb629d6faa864aa0829d59997b07
sgbaird added a commit to sparks-baird/xtal2png that referenced this issue May 23, 2022
mgedmin added a commit to mgedmin/qr2text that referenced this issue Nov 11, 2023
samjwu added a commit to ROCm/rocm-docs-core that referenced this issue Nov 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants