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 trialErion Vlada
13,496 Pointsimport monster
In the video you show importing the whole monster file(import monster), which in turn will give access to all of its classes, Dragon, Troll etc.
To create a dragon for example, you would do this new_dragon = monster.Dragon()
I imported all classes like this, from monster import * (* for all classes), this way I only have to call the class directly, for example new_dragon = Dragon() as before.
My Question(s):
- Is there anything wrong with this way?
- Are there Speed or Memory usage differences?
Thanks
3 Answers
Kenneth Love
Treehouse Guest TeacherThe problem is that there might be something in monster
that has the same name as something you've already created or imported in the current file. Or you might be relying on something being from monster
but you then import or create something with that same name. Either way, your stuff from monster
has now either clobbered the local stuff or been clobbered by the local stuff.
Keeping it as import monster
puts everything into the monster
namespace so you don't have to worry about overwriting anything.
Chris Freeman
Treehouse Moderator 68,454 PointsIn python, explicit is better than implicit. Importing using "*" works but should be avoided [PEP8] "... as they make it unclear which names are present in the namespace". If you don't want to type the module name each time as module.Dragon()
, you can import each class:
from monster import Dragon, Troll
Though most style guides want imports on a separate line:
from monster import Dragon
from monster import Troll
The speed difference is minimal unless the imported module is huge.
Kenneth Love
Treehouse Guest TeacherThe only argument for import *
is when it's convention in a given library (Peewee, for example). It chafes a lot of us but even PEP 8 says to follow conventions over style guide rules.
Erion Vlada
13,496 PointsThanks guys, much appreciated