Making python imports more structured?

Once you've used pylint to identify duplicate and unused imports, and organized them according to PEP8 as the other answers suggest, you can further clean it up by changing the way you import packages.

Instead of

from google.appengine.api import urlfetch, taskqueue, users, images

you could just do

from google.appengine import api

then you would need to put "api.urlfetch", "api.taskqueue", etc. wherever you use those.

This isn't the "right" way to do it, it's just another way. You'll have to choose which one you prefer.

Also note that you can use aliases:

from google.appengine import api as gaeapi

now you would put "gaeapi.urlfetch". This is useful if you need to import modules called "api" from multiple packages.

Also, to answer your question "Why can't I specify the same import for multiple files at one place and I must spec the same import in both files?", if you're importing the same packages in multiple files, that could indicate those files are closely related, and should be merged into a single file. Unlike C++ or Java, where every class is its own file, the pythonic way is to make each module (file) as self-contained as possible, which usually means they contain multiple classes and functions.


PEP 8 - Style Guide for Python code recomends to order your imports in following order:

1. Standard library imports
2. - blank line -
3. google sdk imports
4. - blank line -
5. django imports
6. - blank line -
7. your own code imports

Import only things you use in code. Remove unused imports. You can use one of these tools to detect unused imports: Pydev on Eclipse / pyflakes / pylint

You have quite a lot imports. How big is your actual code? It might be a good idea to split it into few modules.

Why can't you import single time in single file? Well you actually could do it like this:

WARNING: THIS EXAMPLE ILLUSTRATES BAD CODING PRACTICES

import_all.py:

    import a
    import b
    import c

other.py:

     from import_all import *

But please don't do that. It is against all good practices of Python development and against The Zen of Python:

Explicit is better than implicit.

...

Namespaces are one honking great idea -- let's do more of those!

I also recommend you to read the Python documentation on modules and something about Python namespaces.

Tags:

Python

Import