Turtle Module in python not importing

J.L picture J.L · Aug 24, 2015 · Viewed 17.5k times · Source

this is my fist time using the turtle module in python but i can't seem to import it?
Here's my code:

from turtle import *

pen1 = Pen()
pen2 = Pen()

pen1.screen.bgcolour("#2928A7") 

and here is the error I get:

Traceback (most recent call last):
  File "C:\Python34\Python saves\turtle.py", line 2, in <module>
    from turtle import *
  File "C:\Python34\Python saves\turtle.py", line 5, in <module>
    pen1 = Pen()
NameError: name 'Pen' is not defined

Can anyone tell me what I did wrong?

Answer

PM 2Ring picture PM 2Ring · Aug 24, 2015

The problem is that you've named your program "turtle.py".

So when Python sees the statement
from turtle import *
the first matching module named turtle that it finds is your program, "turtle.py".

In other words, your program is basically importing itself and not the turtle graphics module.


Here's some code to demonstrate this problem.

turtle.py

#! /usr/bin/env python

''' Mock Turtle

    Demonstrate what happens when you give your program the same name
    as a module you want to import.

    See http://stackoverflow.com/q/32180949/4014959

    Written by PM 2Ring 2015.08.24
'''

import turtle

foo = 42
print(turtle.foo)
help(turtle)

I guess I should show what that code actually prints...

When run as turtle.py it prints the following "help" info:

Help on module turtle:

NAME
    turtle - Mock Turtle

FILE
    /mnt/sda4/PM2Ring/Documents/python/turtle.py

DESCRIPTION
    Demonstrate what happens when you give your program the same name
    as a module you want to import.

    See http://stackoverflow.com/q/32180949/4014959

    Written by PM 2Ring 2015.08.24

DATA
    foo = 42

(END) 

When you hit Q to get out of the Help, the Help info is displayed again. When you hit Q for the second time, then

42

42

is printed.

Why are the "help" message and 42 printed twice? That's because all the code in turtle.py is executed when it's imported, and then again when its encountered after the import statement. Note that Python doesn't try to import modules that it has already imported (unless explicitly told to do so with reload). If Python did re-import, then the above code would get stuck in an infinite loop of importing.


When run as mockturtle.py it prints:

Traceback (most recent call last):
  File "./mock_turtle.py", line 16, in <module>
    print(turtle.foo)
AttributeError: 'module' object has no attribute 'foo'

And of course that's because the standard turtle module doesn't actually have a foo attribute.