Reputation: 2843
What is the pythonic way to import from Models (or Forms or views) in Django?
To say it frank I bluntly do this:
from myapp.models import foo, bar, foobar, barfoo, foofoo, barbar, barfoobar, thelistgoeson, and, on, andon...
It is far longer than the maximum of 79 characters - but what is the better way to do this?
Upvotes: 2
Views: 400
Reputation: 4698
What about importing models?
from myapp import models
foo = models.foo
bar = models.bar
It is much shorter and you don't have to maintain a list of imports. You also get to have a namespace, and you can have local variables called foo
and bar
Upvotes: 2
Reputation: 76907
Use parentheses to group your imports together:
from myapp.models import (foo, bar, foobar, barfoo, foofoo,
barbar, barfoobar, thelistgoeson, and, on, and, so, on)
This is in accordance with PEP-328 Rationale for parentheses:
Currently, if you want to import a lot of names from a module or package, you have to choose one of several unpalatable options:
- Write a long line with backslash continuations:
- Write multiple import statements:
(
import *
is not an option ;-)Instead, it should be possible to use Python's standard grouping mechanism (parentheses) to write the import statement:
This part of the proposal had BDFL approval from the beginning.
Parentheses support was added to Python 2.4.
Upvotes: 7