2

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?

Joe
  • 965
  • 11
  • 16
  • 1
    I think it would be best to raise an issue on github for this here: https://github.com/mypyc/mypyc/issues I am having exactly the same issue on Windows 10 python 3.10 - seems like a bug to me and github is going to be the best way to get their attention. – AustEcon Dec 24 '21 at 14:48
  • Thanks @AustEcon, I just filed an issue at the link you suggested: https://github.com/mypyc/mypyc/issues/912 – Joe Dec 24 '21 at 18:59
  • I found that I could reliably overcome this issue by either blowing away and then recreating the virtual env, or, even better, docker system prune. – Joe Apr 06 '23 at 15:18

2 Answers2

2

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
0

Using importlib.resources also works with mypyc!

Javier
  • 2,752
  • 15
  • 30