I am experimenting with how to package my python code as a zip archive. I understand there are other ways to share and distribute code. Right now I am specifically interested in how to get this to work as a zip archive.
Here is a MWE. This works fine when I use it as a regular package.
main.py
TestPackage/
TestPackage/__init__.py
TestPackage/PackA/PackA.py
TestPackage/PackA/__init__.py
# TestPackage/__init__.py
import TestPackage.PackA
# TestPackage/PackA/PackA.py
def hello_from_A():
print('Hello from A!')
# TestPackage/PackA/__init__.py
from .PackA import *
# main.py
from TestPackage.PackA import hello_from_A
hello_from_A() # Hello from A!
I'd like to make TestPackage into a zip archive that I can say, send to a friend. Then they could use it like so.
main.py
TestPackage.zip
# main.py
import sys
sys.path.append('/path/to/zip/dir/TestPackage.zip')
from TestPackage.PackA import hello_from_A
hello_from_A()
I created TestPackage.zip by cd'ing into TestPackage/ and doing
zip ../TestPackage.zip *
But the problem is that when I try to run main.py as I show above with the zip archive I get the following error:
Traceback (most recent call last):
File "main.py", line 6, in
from TestPackage.PackA import hello_from_A
ModuleNotFoundError: No module named 'TestPackage'
Why is python not finding TestPackage? Is this because of the level in the file structure that I created the zip? Any suggestions on how I can get this working?