How to shortcut a package path?

P

Pedro Werneck

on dir1/__init__.py:

import dir2.program
program = dir2.program


But why do you want to do this ?


On 16 Aug 2003 17:05:46 -0700
 
S

sdhyok

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


Thanks in advance.

Daehyok Shin
 
G

Graham Fawcett

sdhyok said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top