'Is there support in python to *import* a gzipped file?

Assuming I have a gzipped mymodule.py.gz I hoped that python (maybe with some parameters) could import it with:

import mymodule

(I would imagine that when a .py file is not found, then .py.gz is looked for.)

or maybe there is a specific version of import:

gzimport mymodule

I would not want to uncompress the file if possible. I guess, I could just uncompress it (from within python maybe to /tmp) and import it as normal. But I would rather not do that if I do not have to.) Other compression formats would also be of interest.



Solution 1:[1]

Since you mentioned "other compression formats would also be of interest":

This actually works out of the box for .zip format. You just need to have the zipfile on the sys.path (just the same as any other directory containing .py files available for importing).

$ echo 'print("hello world")' > mymodule.py
$ zip -o example.zip mymodule.py 
  adding: example.py (stored 0%)
$ rm mymodule.py 
$ python3
Python 3.10.2 (main, Feb  2 2022, 06:19:27) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append("example.zip")
>>> import mymodule
hello world

It works because there is a zipimporter active by default:

>>> mymodule
<module 'mymodule' from 'example.zip/mymodule.py'>
>>> mymodule.__loader__
<zipimporter object "example.zip/">

To get it working for .gz format, you could add support fairly easily by adding a gzip importer to the sys.meta_path.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1