Skip to content
Advertisement

ModuleNotFoundError with setup.py using a compiled pyc module

I can normally import a compiled .pyc module as well as .py, but when trying to package a simple project with setup.py, I’m getting the ModuleNotFoundError exception for the compiled .pyc module. Because this is only happening when using setup.py, otherwise is working fine, I don’t know if there’s something I should had to setup.py to make this work.

The project structure is currently something like this:

JavaScript

and the setup.py:

JavaScript

The main.py:

JavaScript

If I just try to import FAILING.pyc on the repl everything works as expected:

JavaScript

But if I first run python3 setup.py intall and then call proj I’m getting the following error:

JavaScript

I’m also running this inside a virtualenv environment, although I’m guessing this is not related to the error.

What am I doing wrong, or what would I need to change to make this work?

Advertisement

Answer

Here is a small demo which builds a source distribution and wheel that contains a .pyc file

note that I’ve removed most of the cruft from your example as the cython stuff is unrelated to your problem

JavaScript

there’s a few things to note about the setup.py:

  • I include in packages the package that has the .pyc files — I could have used setuptools.find_packages instead, but this was simpler
  • The .pyc file is included as package_data — by default pyc files are not packaged as they’re generally leftover build artifacts
  • I need to compile the pyc into the legacy location using the -b flag of python3 -m compileall
  • even a “compiled” pyc file does not obfuscate the actual code, it can be recovered using dis for example — when you talk about “compiled” here it just means it has been transformed into the (still relatively high level) python bytecode

From either the source distribution or the wheel, you can install the package.

For example running the script:

JavaScript

Afterwards, I can install this package and use it:

JavaScript
Advertisement