zip files as nested modules?

Discussion in 'Python' started by tsuraan, Apr 1, 2007.

  1. tsuraan

    tsuraan Guest

    Supposing that I have a directory tree like so:

    a/
    __init__.py
    b/
    __init__.py
    c.py

    and b.py has some method (let's call it d) within it. I can, from python, do:

    from a.b.c import d
    d()

    And, that works. Now, suppose I want to have a zipped module under a,
    called b.zip. Is there any way that I can accomplish the same thing,
    but using the zip file as the inner module?

    My directory layout is then

    a/
    __init__.py
    b.zip

    And b is a zipfile laid out like

    b/
    __init__.py
    c.py

    I tried populating a's __init__ with this:

    import zipimport
    import os
    here = os.path.join(os.getcwd(), __path__[0])
    zips = [f for f in os.listdir(here) if f.endswith('.zip')]
    zips = [os.path.join(here, z) for z in zips]

    for z in zips:
    print z
    mod = os.path.split(z)[-1][:-4]
    print mod
    globals()[mod] = zipimport.zipimporter(z).load_module(mod)

    All the zip modules appear (I actually have a few zips, but that
    shouldn't be important), but their contents do not seem to be
    accessible in any way. I could probably put import statements in all
    the __init__.py files to import everything in the level below, but I
    am under the impression that relative imports are frowned upon, and it
    seems pretty bug-prone anyhow.

    Any pointers on how to accomplish zip modules being nested within normal ones?
     
    tsuraan, Apr 1, 2007
    #1
    1. Advertising

  2. Importing modules from zip files was proposed in PEP-273 [1]

    Here is how the spec of PEP-273 begins:

    '''
    Currently, sys.path is a list of directory names as strings. If this
    PEP is implemented, an item of sys.path can be a string naming a zip
    file archive.
    '''

    My interpretation of the above is that, to be importable, a zip file
    must be explicitly named in sys.path.

    So the mere fact that a zip file lies somewhere in a directory which
    is part of the sys.path does not make it importable.

    Cheers,

    Luciano


    [1] http://www.python.org/dev/peps/pep-0273/
     
    Luciano Ramalho, Apr 6, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alex Hunsley
    Replies:
    1
    Views:
    605
    Andrew Thompson
    Sep 16, 2004
  2. Replies:
    0
    Views:
    1,740
  3. Graham Wood
    Replies:
    3
    Views:
    554
    A. Sinan Unur
    Jan 11, 2004
  4. MoshiachNow
    Replies:
    2
    Views:
    276
    Ilya Zakharevich
    Oct 4, 2006
  5. Bo Yang
    Replies:
    9
    Views:
    308
    -berlin.de
    Nov 20, 2006
Loading...

Share This Page