How to shortcut a package path?

Graham Fawcett fawcett at teksavvy.com
Sun Aug 17 01:22:34 EDT 2003


sdhyok wrote:

>Is there any way to create a shortcut for a package path?
>For instance, if I have the following path structure,
>
>dir1/dir2/program.py
>
>what should I do if I want to import program with
>
>from dir1 import program
>
>, not with
>
>from dir1.dir2 import program
>
>  
>

If it were me, I would lay it out as such:

    #----------------------------------------------------------
    # myapp.py

    from dir1 import program


    #----------------------------------------------------------
    # dir1/__init__.py

    from dir1.dir2 import program  

    # or, from dir2 import program, see note below.



    #----------------------------------------------------------
    # dir1/dir2/__init__.py

    """Required, of course"""


    #----------------------------------------------------------
    # dir1/dir2/program.py

    """Your code"""


Side note: In dir1/__init__.py, I used "from dir1.dir2 import program" 
instead of "from dir2 import program". Either one would work, but 
sometimes you have to be careful not to mix the two (the absolute and 
the relative) approaches. Mixing them can lead to the a module being 
initialized twice, which can sometimes lead to some strange and 
hard-to-debug behaviour. Given the Python zen-ism of "explicit is better 
than implicit", my vote is for the side-effect-free, "full path" approach.

Here's one of many c.l.py threads that refers to this 
double-initialization behaviour (maybe not the best, but the first I found):

    http://tinyurl.com/k98r


Pedro asked why you want to do this... Personally, I might use this 
technique would be if I wanted "dir1" to act as a Facade, or API, to a 
set of subpackages. Import all of the "public" classes and functions 
into the dir1.__init__ module, and then your users are less inclined to 
access your "private" subpackages. This isn't a security technique, of 
course, it's just clean API design.

-- Graham







More information about the Python-list mailing list