hal_v
hal_v

Reputation: 151

Importing Turtle graphics modules

I admit I have just started with turtle graphics in Python 3.3, and following a youtube presentation started with from turtle import *. This allows such short commands as fd(100) in place of the format I see more often turtle.forward(100) etc.

My questions are:

  1. In using this format am I using an unacceptable shortcut?
  2. How can I stop Python IDLE from interpreting every command in this format as "Turtle graphics"?
  3. Does the " * " suffix mean as it usually does, "everything"?

I apologize in advance if I should not be asking multiple questions in one post, but they are relevant to each other and this seemed logical.

Upvotes: 1

Views: 2161

Answers (2)

user3449531
user3449531

Reputation:

By using from package import * you're just importing everything optionally defined in an __init__.py file's __all__ variable defined by the package you are importing from. __all__ variable may be omitted and that's why you should read the details

Most of the time I'd use "import package" just to avoid polluting the namespace.

Upvotes: 0

Michael0x2a
Michael0x2a

Reputation: 63998

Generally, yes, you do want to avoid using the form from module import *. That that does is that it opens up the module (a normal python file), and essentially takes every function, class, etc. defined within that file and adds it to your namespace. And you're right -- * does mean "everything".

So, if I wrote a module named foo.py that contained a function named bar1, bar2, etc, doing from foo import * would allow me to use these functions as if I had defined it within my current file:

from foo import *

bar1()
bar2()
# etc

The main reason why this is bad is that it takes an unknown amount of functions and classes and dumps it into your namespace. It makes it hard to track what's going on in larger codebases when you suddenly start using a function out of the blue. For example:

from a import *
from b import *
from c import *
# etc

example()
# Where did this come from? From module a, b, or c? What if both a and b define a 
# function named 'example'? 

You're already aware of the import module; module.function form, but there's a third form which is also useful:

from turtle import fd, right, left  # etc

right(90)
fd(100)
backwards(300) # throws an error!
forwards(300)  # throws an error!

Now, I can cherry-pick the functions I want, know where they come from, and avoid polluting my namespace.

However, in your case, I wouldn't worry too much about it. Since you're experimenting and learning how to use the turtle module, I think it's more important to focus on that aspect rather then writing perfectly idiomatic Python.

Upvotes: 2

Related Questions