What is the difference between `import turtle` and `from turtle import *`?

13.1k views Asked by At

Besides the syntactic differences, I do not understand what the difference between import turtle and from turtle import * is, as both methods appear to produce the same result:

Method 1

import turtle

t = turtle.Pen()

# rest of program...

Method 2

# Method 2:

from turtle import *

t = Turtle()

# rest of program...

One Internet tutorial I followed used Method 1 and another used Method 2. What is the difference between the two and when should I use each one?

3

There are 3 answers

3
Malik Brahimi On BEST ANSWER

Method 1

You are simply importing the package turtle and as you may already know, you are unable to use a variable that has not been declared. Thus, you must reference every item with the package name as a prefix like turtle.Pen or turtle.Turtle.


Method 2

You are not importing the package turtle and thus you can not use it at all. In fact, you are actually importing every member from the namespace and thus you can just use the names of the items as is as seen in Pen or Turtle which are defined to be inclusive of the namespace.

0
Alex Huszagh On

Besides purely semantics, there's very good reason to not do:

from module import *

It pollutes the namespace and you have no easy way of finding what you just included.

By stating:

import module

You load the module into the namespace but restrict everything within. This lets you know precisely what you imported, and so if you have module.a and a defined, you don't have to worry about over-writing module.a.

It has the same import statement, as the link above.

The rest depends on the package structure: specifically whether the module leaves a blank init.py or defines the modules via all = [...]

If all is defined, it imports as those submodules, if not, it imports the module and then renames the submodules.

As shown here, the import * variety is highly discouraged (some Pythonistas have even stated they wished it was never allowed): What exactly does "import *" import?

0
Alex Ivanov On

"import turtle brings" the module and "from turtle import *" brings objects from the module.

If I do

import sys

I type

sys.exit()

if I do

from sys import *

I type just

exit()