who needs social life when you have broadband?

Inventas vitam iuvat excoluisse per artes / Let us improve life through science and art.

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):

PYTHON:
  1. def func_test():
  2. "Simple function"
  3. 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:

PYTHON:
  1. # importing the zipimport
  2. import zipimport
  3.  
  4. # create the zipimporter object
  5. zip = zipimport.zipimporter("pymod.zip")
  6. # load the module
  7. mod = zip.load_module("test")
  8.  
  9. # and now, the magic:
  10. test.func_test()
  11.  
  12. "Function test, pythowned !"

There is another way which you can do that, and python will use the zipimport implicitly:

PYTHON:
  1. import sys
  2.  
  3. sys.path.insert(0, "pymod.zip")
  4.  
  5. import test
  6.  
  7. test.func_test()
  8.  
  9. "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