Separate namespace from file hierarchy?

Diez B. Roggisch deets at nospam.web.de
Tue Oct 20 16:09:01 CEST 2009


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()
> ####################
> 
> 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.
> 
> In C++, I can define namespace independent of file hierarchy (as shown
> in the following code). I'm wondering if there is a way to make the
> namespace separate from the file hierarchy in python.
> 
> #include <dirname/A.hpp>
> #include <dirname/B.hpp>
> 
> int main() {
>    dirname::A a = dirname::A()
>    dirname::B b = dirname::B()
> }

you can define 

  dirname.both.__init__.py

and in that

  from A import A
  from B import B

Then you have your namespace.

Diez



More information about the Python-list mailing list