4

I have heard that "import *" is not considered good practice.

So for example, in a Django app, I have created 5 models, and I want an admin page for each, is this still considered bad practice an my admin.py file?

from myapp.models import *

edit: Its my own code, I know that I want to import everything from the file.

wobbily_col
  • 11,390
  • 12
  • 62
  • 86
  • 1
    It is a source of bugs; you don't know what names are going to be imported from the line alone. See [this recent question](https://stackoverflow.com/questions/29587933/attributeerror-module-object-has-no-attribute-choice) where the problem was the `from scipy import *` line. – Martijn Pieters Apr 14 '15 at 13:37
  • Well that's kind of the point of my question, I do know what I am importing, as its my own code. – wobbily_col Apr 14 '15 at 13:38
  • But will you later on still remember where you used `import *` as your project evolves? – Martijn Pieters Apr 14 '15 at 13:40
  • probably, I work with it every day and have a good idea of the data model. – wobbily_col Apr 14 '15 at 13:44
  • 3
    If you are the *only* person who works with the code, it doesn't really matter what you do. If any one else is using the code, are you sure *they* will remember where `import *` is used? – chepner Apr 14 '15 at 13:49
  • @wobbily_col: so how confident are you that the project remains small enough and unimportant enough that this issue will never crop up? Why expose yourself to the risk? – Martijn Pieters Apr 14 '15 at 14:59
  • Its not small. It is important. But I still know what my models are. That's my job. Anyway, I like the suggestion below to import the models and use that when referencing each one. – wobbily_col Apr 15 '15 at 07:57

1 Answers1

4

Yes. The problem is that may add more code in the future that could cause unexpected issues; such as naming conflicts.

I normally go with:

from myapp.models import MyModel
from myapp.models import MySecondModel

An alternative would be:

from myapp.models import (MyModel, MySecondModel)

Edit:

As @kalhartt pointed out you can also simply do.

from myapp import models

And then use models.MyModel etc if you have to import a lot of classes.

Community
  • 1
  • 1
eandersson
  • 25,781
  • 8
  • 89
  • 110