Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypyc, KeyError: '__file__'

Tags:

mypy

mypyc

I successfully use mypyc in my project and it has performed well until just a couple days ago. I now get the following error:

File "mypyc/__main__.py", line 18, in <module>
KeyError: '__file__'

Line 18 above, i.e., the line that is failing, is just

base_path = os.path.join(os.path.dirname(__file__), '..')

which I wouldn't expect to fail. I am in my venv virtualenv when I execute mypyc using the same command as has always worked before.

I thought perhaps a regression was introduced in mypyc so I used git to go back in time to see if that line had changed in any recent version of mypy, but it hadn't.

I also tried downgrading mypy to an older version that worked before but that version also failed with the same error. To be sure it wasn't being experienced by others I also checked the issues at the mypy repo on github and did a search for __file__ to see if that part of the error message showed up and it didn't. Perhaps it is some weird issue with my environment?

I experience the issue with venv virtualenvs created with Python 3.10, 3.10.1 but also 3.9.9 too. It worked fine on Python 3.10 before. Any ideas on what to investigate next?

like image 312
Joe Avatar asked Sep 12 '25 21:09

Joe


1 Answers

Here is a workaround getting path of current script file without using '__file__' variable:

import inspect
def get_module_path() -> Any:
    """
    Function replaces the usage of the '__file__' variable which generates an error after
    the script is compiled with mypyc.
    """
    # Get the current call stack
    stack = inspect.stack()
    # Get the filename of the current file
    filename = stack[1].filename
    # Get the directory path of the current file
    dirname = os.path.dirname(filename)
    return dirname
like image 187
Jarosław Wieczorek Avatar answered Sep 14 '25 16:09

Jarosław Wieczorek