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) Inheritance DRY

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Does importing also import other imports?

When Kenneth Love creates the Combat class (combat.py) he imports random.

Then in the Monster class (monster.py) he imports `from combat import Combat'. (at about 3:10 in the video).

My question is... in combat.py, random has been imported. In monster.py, random has also been imported and then on another line, Combat is imported. So in monster.py, do we still need to import random or will that come with the Combat import?

4 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

In addition to what Jeff Wilton said, if monster.py had used the not-recommended import style from combat import *, then the import would grab everything from combat including its imports. This is dangerous because then monster.py would be relying on implicit importing of modules existing in another file. If combat.py changes, and removes its import of random, monster.py could break if it required random. Best to explicitly import everything you need in each file. "Explicit is better than Implicit!"

Jeff Wilton
Jeff Wilton
16,646 Points

You need to explicitly import anything that will be used in that file, otherwise it will throw an error at runtime.

NameError: name 'random' is not defined

MOD NOTE: Changed to Answer so it may be upvoted / marked as Best Answer.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You should use explicit imports everywhere. DO THIS

However, just to add to the fun of the thread, let's assume we have:

monster.py

import random

class Monster:
    ....

other_file.py

import monster

hydra = monster.Monster()

In other_file.py, I can use monster.random to get access to the random library. That said, this is highly breakable and probably shouldn't be done in 99.9999999% of cases.

Yes, you would still need to

import random

because in the video, he doesn't import the whole combat.py file. He only picked out Combat (a function) from combat (the python document); he didn't actually import the entire file with the import already in it.

but like Chris said, "Explicit is better than Implicit!"