Python implicit zipimport
Hello ! This is my first post on this blog, so I hope you enjoy =) This post is about an feature called zipimporter who easy helps you in distribution or organization of modules and packages.
Well, since 2.3 version of Python, there is a module called zipimporter, the main objective of this module is:
" This module adds the ability to import Python modules (*.py, *.py[co]) and packages from ZIP-format archives."
As you see, it's not Java which only have .jar (very slow) compression of packages.
So, we let's code and stop talking:
First, we create a simple module called test.py with this simple code (do not forget the indentation):
-
def func_test():
-
"Simple function"
-
print "Function test, pythowned !"
Later, we save that test.py and compress it inside pymod.zip, now we can use the .zip with compressed module, let's see:
-
# importing the zipimport
-
import zipimport
-
-
# create the zipimporter object
-
zip = zipimport.zipimporter("pymod.zip")
-
# load the module
-
mod = zip.load_module("test")
-
-
# and now, the magic:
-
test.func_test()
-
-
"Function test, pythowned !"
There is another way which you can do that, and python will use the zipimport implicitly:
-
import sys
-
-
sys.path.insert(0, "pymod.zip")
-
-
import test
-
-
test.func_test()
-
-
"Function test, pythowned !"
Some python modules are really small and imperceptible, but can help you a lot in the distribution of a huge project.
- Christian S. Perone
No comments yet. Be the first.
Leave a reply
