import syntax in Python - python

Is there any difference between coding:
import turtle
and coding
from turtle import *
(Using module turtle as an example, I suppose the answer will be true for all modules.)
My understanding was that the * imports all methods in the module, so why use the longer syntax?

Related

ModuleNotFoundError: No module named 'Tkinter' in python using python 3 [duplicate]

This question already has answers here:
ImportError: No module named 'Tkinter'
(27 answers)
Closed 5 years ago.
I get the error ModuleNotFoundError: No module named 'Tkinter' in Python 3. I am trying to run this piece of code.
from swampy.TurtleWorld import *
import Tkinter
world = TurtleWorld()
bob = Turtle()
fd(bob, 100)
lt(bob)
fd(bob, 100)
print (bob)
wait_for_user()
It doesn't look like your code is using Tkinter at all, so you could just remove the line import Tkinter. In any case, you should be able to import Tkinter in Python always, because it is built into the standard library; the problem is that the module is named tkinter in lowercase, not Tkinter, so it should be:
import tkinter
But again, if you are not going to use the module it would be clearer to remove that import statement.
The way you are importing Tkinter uses the capitalization for Python 2. In Python 3 Tkinter has a lower case 't'. So for Python 3 you would write it as:
import tkinter
To make their programs work in both Python 2 and Python 3 I have seem many people write their code in the following manner:
try:
import Tkinter
except:
import tkinter
With the above you will have the correct import for whether you or not you are using Python 2 or Python 3. I'd also recommend setting up as value for tkinter such as:
import tkinter as tk
This way while you are programming instead of writing tkinter.Frame() you can shorten it to tk.Frame(). It makes it a lot quicker to code Tkinter programs.
I am assuming you are planning on implementing Tkinter later in your code as currently your code makes no use of it, so I hope this helps. If you are not going to add anything using Tkinter, I would recommend removing the import.

Using the wrong module

I'm programming a game with pygame, but when I try to use the python's math module, my program tries to use pygame.math instead. How can I solve this issue?
Example:
import pygame, math
from pygame import *
pygame.init()
a = math.sin(90)
# some code that uses a
Error message:
AttributeError: module 'pygame.math' has no attribute 'sin'
The error might be because of from pygame import *, but my code doesn't work without it.
Solved in the commments:
Use the code as following, as it will prevent errors:
import pygame
import math
pygame.init()
a = math.sin(90)
This way it imports as separate modules. You had it saying:
Import Pygame and Pygame Math
Initiate Pygame
define variable "a"
I use pygame and math in my code but I have them as separate imports:
import pygame
import math
And everything works as expected without error

What is the correct way to arrange unwieldy imports

I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.
I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.
File my_main_file.py
import os
import sys
import inspect
...
import gvars
import Common
...
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
...
import menus.config
File gvars.py (also calls Tkinter)
from Tkinter import Text
from Tkinter import Tk
import Tkinter
File Common.py (also calls gvars and os)
import gvars
import tkFileDialog
import os
From Menus/config.py (also calls Common, gvars and Tkinter)
import Common
import gvars
import UIFunctions
import Tkinter
# Imports from Tk
from Tkinter import END
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
And on and on it goes... As you can see this is a mess I inherited. I know there are issue here (like "import blah" followed by "from blah import yuck"). I'm just looking for the most pythonic way to handle this.
Do I only need the imports in my_main_file.py? I.e. will Common.py code be able to access os. methods if "import os" is removed from the module and i=is only in the main script.
Is it best to have imports that are only referenced in a module imported in that module even though they are the similar? I.e. "from Tkinter import Text" in one module and "from Tkinter import END" in another.
Side question - which is better?
import Tkinter
or
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
from Tkinter import Scrollbar
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
from Tkinter import Entry
from Tkinter import LEFT, RIGHT, TOP, BOTTOM
from Tkinter import DISABLED
from Tkinter import X, Y, BOTH
from Tkinter import VERTICAL, HORIZONTAL
from Tkinter import Listbox
from Tkinter import Frame, LabelFrame
from Tkinter import Entry
from Tkinter import N,S,E,W
from Tkinter import BROWSE, EXTENDED
from Tkinter import DISABLED, NORMAL
According to the PEP8 styleguide (one of the most authoritative sources on what is pythonic) using wildcard imports (from ... import *) should be avoided unless you are republishing an interface, which is not your intent.
My suggestion is to import TKinter as tk and refer to tk.WORD etc.
One of the reasons for doing this is that some of the constants and classes from Tkinter are fairly generically named - N, Button, etc.
By referring to tk.N, tk.Button, etc. it makes your intent in the code much clearer.
If one or two specific things are imported, then:
from Tkinter import END, Toplevel, ...
If pretty much everything in that module is imported, then:
from Tkinter import *
If more than a bunch of functions and classes are imported, then:
import Tkinter
Or more pythonic:
import Tkinter as tk
I am not sure if we can have common file to import all common modules. I think, for all of the files which you mentioned in question, you need to have separate imports.
About your side question, it is better to import specific function, method from class. You should import only those methods, functions which are being used in file. if you just do import Tkinter, then you have to use it like Tkinter.Menu, Tkinter.WORD etc in your code. Then it might be difficult to read if some library or module's functions have been used at lot of places in your file. So its better to import all required methods, functions from module and use them. You can import many functions from same library in one liner.
The way I've solved this in the past is to have an __init__.py file in each folder where the sources exist, then all your imports can go in there
There are even better ways of organizing python files. For more information on how to organize modules, see the official documentation
docs.python.org
stackoverflow
Also checkout importanize
Agree that from Tkinter import * is best avoided.
One way I found to deal with long imports on any given module. Not totally clean, but less wordy than the 1 per line repeats you have.
I would have done it with your TKinter import list, but I don't have it installed, so using sys instead.
#opening a parenthesis allows for implicit line feeds
from sys import (
stderr, stdout, stdin, #could have more...
#dont need this anymore
# maxint,
#maxsize, #dont this need anymore either
argv,
)
print globals().keys()
output:
['stdout', '__builtins__', '__file__', 'stdin', 'argv', '__package__', 'stderr', '__name__', '__doc__']

Problems importing Turtle (Python 3.5)

I'm trying to use Turtle, but for some reason, it won't let me import it. I've tried from turtle import * (and that works) but if I try print(dir(turtle)) or to use any functions, I get an error saying turtle is not defined.
from turtle import Turtle doesn't work but print(dir(Turtle)) after using from turtle import * does work. However, prefixing commands with Turtle. ie Turtle.color("red") doesn't work.
Also, the demonstrations in the turtledemo folder work. I'd really appreciate any help
This imports turtle into the main namespace and is used as follows:
import turtle
turtle.something()
Thus, you now have an identifier in your main namespace, named turtle.
This imports all visible identifiers from turtle into the main namespace
and is used differently:
from turtle import *
something()
In this scenario, turtle is not in the main namespace. Its contents
are. Thus, dir(turtle) will fail, because that identifier isn't there.
Are you sure that from turtle import Turtle doesn't work? It worked
for me.
If you import all from turtle then you have to use the Turtle object directly, like this:
from turtle import *
print(dir(Turtle))
and not like this:
from turtle import *
print(dir(turtle))

Python: Making Background Image with Turtles

I am trying to insert a .gif file as a background image in my turtle world for a separate turtle to travel on, but I can't get it to work. I'm new to python and any help would be great.
Here's the current code:
from turtle import *
from Tkinter import *
def test():
turtle.bgpic("warehouse1.gif")
fd(100)
goto(50, 100)
from turtle import * makes available all names in the turtle module so you could use bare bgpic() in this case:
#!/usr/bin/env python
from turtle import *
def test():
speed(1) # set the slowest speed to see the turtle movements
bgpic('warehouse1.gif')
fd(100)
goto(50, 100)
mainloop()
test()
Note: In general you should not use wildcard imports (*) outside a Python interactive shell. See Idioms and Anti-Idioms in Python.

Categories

Resources