开发者

Python - structure of application

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
imp开发者_如何学编程ort 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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜