A turtle file won't run, if it's named turtle.py. Why is that?

Viewed 96

I just started with turtle and upon writing a basic code which is as follows:

import turtle

srijan_turtle = turtle.Turtle()
srijan_turtle.forward(100)
turtle.done()

I got this error:
srijan_turtle = turtle.Turtle() AttributeError: partially initialized module 'turtle' has no attribute 'Turtle' (most likely due to a circular import). Did you mean: 'turtle'?

NOTE: The file was saved as turtle.py

Upon searching for a solution regarding the same, I found this answer over here:
AttributeError: partially initialized module 'turtle' has no attribute 'Turtle' (most likely due to a circular import)

One of the answers there said that:
Simply changing the file name to anything other than, turtle.py would rectify the issue. And it did.

But I did not understand why? Could anyone please explain it to me?

2 Answers

import turtle looks for a module called turtle in order to import it. One of the first places Python's importing mechanism looks is the current directory, in a file called turtle.py, so your file imports itself (instead of importing the actual Turtle library that provides turtle functions).

To figure out where the file is located, you can print turtle.__file__:

# without a turtle.py present in the local dir
>>> import turtle
>>> print(turtle.__file__)
C:\Python310\lib\turtle.py

It should logically follow that you can do the same intentionally - you can create a Python file with functions you want to reuse, and import it by its name from another file in the same directory.

You are importing a module named turtle inside a module named turtle. It believes it should import itself, and does not find the actual turtle library.

Related