roy999
roy999

Reputation: 138

How to group mutliple modules into a single namespace?

I have a python3.5 project which I decided to make a one class per module. I decided to do so because i found out my files were very long and I it was hard to me to understand whats going on.

After I made the change I feel like I am repeating myself in each import file:

from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

Is there any way pass that repeat? I would like that my imports will be more like:

from school import Student, ClassRoom, Teacher

Upvotes: 9

Views: 4228

Answers (3)

Rick
Rick

Reputation: 45251

Use an __init__ module to accomplish this. The contents of an __init__ module are evaluated when the parent module/package is imported. Like this:

# __init__.py
from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

This brings Student, ClassRoom and Teacher into the school namespace. Now you can import using the school module as you like.

Caution: it is really easy to pollute your namespace this way. It's probably better to import explicitly in each module the way you started, or to use the approach in this answer and use your classes employing explicit module references (e.g., school.Teacher() instead of Teacher()).

If you feel school.Teacher() is too long, you can shorten things up a bit this way:

import school as sch
teacher = sch.Teacher()

etc etc.

However, on the other hand, if those classes are objects that should be available at the package level, importing them into the package namespace is probably the correct thing to do. Only you can make that determination.

Upvotes: 8

Sede
Sede

Reputation: 61225

I supposed school is a package, if not you need to create a package and put all your modules into the package then create a __init__.py file where you basically glue everything together. You need to use a relative import in your __init__.py file.

You package must now look like this:

school/
__init__.py
student.py
classroom.py
teacher.py

Then you __init__.py must look like this:

from .student import Students
from .classroom import ClassRoom
from .teacher import Teacher

Next only call your class using package name like this:

import school
t = school.Teacher()

Upvotes: 7

C Panda
C Panda

Reputation: 3405

Yes, you can. Just put all the classes in module school.py. That's what Python modules are for. What you just showed us is the Java way(probably) of maintaining namespace through packages. If you still want to go that way then just make a moule all.py and write,

# all.py
from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

and in you main file, write from school.all import Student, ClassRoom, Teacher But you can see that's redundant and ugly.

Upvotes: -1

Related Questions