0

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 2
    as per your code, `t` is the result of the function `pen()`. It's the pen dictionary, and has no `forward`method, and even less a `pen.forward()` thing. see https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.pen . `turtle.forward(10)` should work, though. – Pac0 Jun 06 '20 at 00:39
  • Wait, why are you doing anything with `pen`? `turtle.pen` is used to configure pen attributes. It doesn't have anything to do with what you're trying to do. – user2357112 Jun 06 '20 at 00:40
  • Moving the default turtle forward would be `turtle.forward(10)`, not `t.pen.forward(10)`. – user2357112 Jun 06 '20 at 00:42
  • The `import` difference is covered in many other postings. The basics of moving a turtle are covered in any `turtle` tutorial. Please refer to these before posting here. – Prune Jun 06 '20 at 00:58

1 Answers1

1

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.

cdlane
  • 40,441
  • 5
  • 32
  • 81