Separate namespace from file hierarchy?
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Oct 20 17:58:28 EDT 2009
On Tue, 20 Oct 2009 08:51:44 -0500, Peng Yu wrote:
> Suppose I have the dirname/both.py, which has the definitions of classes
> A and B. I can use this module in the following code.
>
> #################
> import dirname.both
>
> a=dirname.both.A()
> b=dirname.both.B()
Have you tried this, or are you just assuming it will work?
You can't specify an arbitrary directory location for a module. For the
above to work, "dirname" has to be a package, which means it needs a
__init__.py file.
I'll assume from this point on that "dirname" is the name of a package.
> ####################
>
> When the definitions of A and B become too long, it is better that I put
> them in two different files (to improve the maintainability), for
> example, dirname/A.py and dirname/B.py. Now, the code becomes
>
> #################
> import dirname.A
> import dirname.B
>
> a=dirname.A.A() #two A seems redundant
> b=dirname.B.B() #two B seems redundant
> ####################
>
> However, the last two lines are annoying to me, as 'A' and 'B' appears
> twice, which seems redundant.
Saying it is redundant three times is redundant.
If that worries you, then don't do it. You don't *have* to put the class
A in a module A.py, you can call the module anything appropriate:
import dirname.internal
a = dirname.internal.A()
You can arrange your package in whatever way seems sensible to you. What
I tend to do is something like this:
dirname/
+-- __init__.py
+-- A.py
+-- B.py
and then in __init__.py I have this:
from A import A
from B import B
so the caller can do this:
import dirname
a = dirname.A()
b = dirname.B()
without worrying about the internal structure of the package (the
submodules A and B).
--
Steven
More information about the Python-list
mailing list