What's the difference between from turtle import * and import turtle?

Question:

I am trying to use a book on python, and I understand that from turtle import * imports everything into the current namespace while import turtle just brings the module in so it can be called as a class. When I try the latter, though, it breaks.

>>> import turtle
>>> t = turtle.pen()
>>> t.pen.forward(10)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
   t.pen.forward(10)
AttributeError: 'dict' object has no attribute 'pen

However, using from turtle import*, assigning pen to an object and typing command forward works fine. This is not what the book says to do, but it is the only thing that works. What is happening?

Asked By: Trying_to_work

||

Answers:

If the books says something like:

import turtle
t = turtle.pen()
t.forward(10)

then it’s probably a typo for:

import turtle
t = turtle.Pen()
t.forward(10)

where Pen is a synonym for Turtle — we’ve seen that problem here before. (Lowercase pen() is a utility function that’s rarely used except in error.)

I understand that from turtle import * imports everything into the
current namespace while import turtle just brings the module in so it
can be called as a class

My recommendation: use neither. Instead do:

from turtle import Screen, Turtle

screen = Screen()
turtle = Turtle()

turtle.forward(10)
# ...
screen.exitonclick()

The reason is that Python turtle exposes two programming interfaces, a functional one (for beginners) and an object-oriented one. (The functional interface is derived from the object-oriented one at library load time.) Using either is fine but using both at the same time leads to confusion and bugs. The above import gives access to the object-oriented interface and blocks the funcitonal one.

Answered By: cdlane
from turtle import*
screensize(canvwidth=1500,canvheight=1500,bg"black")
Answered By: Zhenphen Zangmo