pythoncompilationdetectionmypyc

How can I detect whether a given Python module was compiled with mypyc?


I have a Python program, and I want to detect whether it was compiled with mypyc or not so I can include this in the version information of the program for debugging purposes. But how can I do this? I tried looking through dev-intro.md in the mypyc docs, but I couldn't find anything useful. I also looked through Differences from Python in the mypy docs, but I couldn't find anything there either.

How can I detect whether a Python module was compiled with mypyc?


Solution

  • I ended up copying the way mypy and mypyc do it, which is just to check whether __file__ ends with ".py" (link to relevant code).

    A sample implementation could be done like this:

    def is_mypyc_compiled() -> bool:
        return not __file__.endswith(".py")
    

    This works for my use-case, but may not work if you're doing something unconventional with your Python source code filenames.