ty icon indicating copy to clipboard operation
ty copied to clipboard

`__file__` import typed as `str | None`

Open sinon opened this issue 5 months ago • 2 comments

Summary

import typing
import os 
from module import __file__ as module_path

typing.reveal_type(module_path). # str | None
os.path.abspath(module_path) # No overload of function `abspath` matches arguments

https://play.ty.dev/4dd59d9f-5dbe-433e-b370-67bbd5575fb2

mypy and pyright both detect the successful import and type the value as str

Version

ty 0.0.1-alpha.15 (0369a3598 2025-07-18)

sinon avatar Jul 21 '25 09:07 sinon

Thank you for reporting this.

__file__ is annotated as having type str | None in typeshed because there are modules for which __file__ is actually None, like namespace modules.

That said, we could probably make an attempt to detect if the __file__ attribute on a given module is str or None, similar to how we already do this for implicit global uses of __file__ (https://github.com/astral-sh/ruff/pull/18071).

sharkdp avatar Jul 21 '25 09:07 sharkdp

See https://github.com/astral-sh/ty/issues/2063 for a similar issue regarding __package__ in the global namespace

AlexWaygood avatar Dec 18 '25 12:12 AlexWaygood