Skip to content

Mypyc should support __file__ #17795

@CoolCat467

Description

@CoolCat467
Contributor

Feature

Mypyc should set __file__

Pitch

Getting installation directory is important when referencing data files included in your package.
Things like this are common:

DATA_FOLDER: Final = Path(__file__).parent / "data"

Currently, mypyc will compile this with no warnings about possible issues and crash with

Traceback (most recent call last):
  <unrelated details>
  File "src/checkers/game.py", line 108, in <module>
    DATA_FOLDER: Final = Path(__file__).parent / "data"
KeyError: '__file__'

There is a workaround for this, doing something like this before hand

if globals().get("__file__") is None:
    import inspect
    __file__ = inspect.stack()[0].filename

but that's messy

Activity

fenchu

fenchu commented on Aug 7, 2025

@fenchu

This is very inconvenient, because __file__ is so commonly used, all my logging modules has this line:

python -m status.cp313-win_amd64.pyd  
Traceback (most recent call last):
  File "<frozen runpy>", line 189, in _run_module_as_main
  File "<frozen runpy>", line 112, in _get_module_details
  File "bin\status.py", line 16, in <module>
    log = logging.getLogger("root.bin." + os.path.basename(__file__).split('.')[0])
KeyError: '__file__'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @fenchu@CoolCat467@AlexWaygood

        Issue actions

          Mypyc should support `__file__` · Issue #17795 · python/mypy