Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Objects Creating Instances

Sam Dale
Sam Dale
6,136 Points

from monster import *

Hi there. This might be jumping the gun, but when I've dinked around with Python on my own I would use:

from monster import *

Instead of:

from monster import Monster

He might get to it in a later course, but is it better to be more specific when importing or is is all right to import in bulk with the *? Thanks!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Using from <module> import * is discouraged because it copies everything from the "<module>" namespace into the current namespace. This muddying of the namespaces can cause collisions and side-effects. If two or more modules were imported using "*" there is no telling where objects come from. If both modules use the same name for an object the second import would overwrite the first import.

The preferred way is to import just the objects you need using "from monster import Monster".

Additionally, as programs grow in complexity, a more general whole-module "import monster" is preferred so inside the code you would type "monster.Monster" to reference Monster. Which makes tracking objects origins easier. Certain well know module objects, such as datetime.datetime are imported as from datetime import datetime, but for lesser know packages import just the module.

It's not about saving keystrokes, but rather about keeping your code clean and organized. While the any code makes perfect sense to the original programmer, to others, or to the original programmer months later, things are much less obvious.

Sam Dale
Sam Dale
6,136 Points

Thanks for all of the information. Really helpful.