2

Morning,

Got a python app I have been working on.

Currently it consits of just a couple of files but as it gets bigger I am creating more and more files and the top of my main python file I am doing

import url_thread
import task_database
import xxxx
import yyyy

and I am going to be adding another class today which is another import!

Is there a way to stick these py files into a folder, and just do import classes/*

Is there a better way I should be doing this?

More, pythonic?

2
  • You know you can do several imports on a line? i.e. import url_thread, task_database, xxxx, yyyy But in general, see what people are saying below about making packages and importing tidily. Avoid using from ... import * unless it's really necessary. Commented Dec 11, 2010 at 21:18
  • Also, you can have more than one class per module! Just in case you're not aware. Commented Dec 11, 2010 at 22:48

3 Answers 3

1

yes, you can do what you are asking, but it is not advised.

you can create a package containing all your modules and then pollute your namespace by just importing everything:

from foo import *

... or a better way would be to create a nicely structured package of modules and then explicitly import them as needed.

Sign up to request clarification or add additional context in comments.

Comments

0

You can make a package and import from that package: from mypackage import *.

1 Comment

Note: That will load __init__ and import from there. Also, be advised that import * has quite a few pitfalls and therefore "considered harmful" in most cases.
0

Don't listen all the stuff people say about "namespace pollution". Go ahead and do from classes import *, if it's convenient for you (and I believe it is), but consider using __all__ in your package.

To be exact, the following folder structure would do it:

classes/
|-- class1.py
|-- class2.py
`-- __init__.py

Adding the file classes/__init__.py creates the package. It looks like this:

from class1 import Class1
from class2 import Class2

__all__ = ["Class1", "Class2"]

Please note the quotes around class names in __all__.

Then, you can use the package in whatever scripts you have:

>>> from classes import *
>>> Class1
<class classes.class1.Class1 at 0xb781c68c>
>>> Class2
<class classes.class2.Class2 at 0xb781c6ec>
>>> dir()
['Class1', 'Class2', '__builtins__', '__doc__', '__name__', '__package__']

Nice and easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.