Issue #27891: Consistently group and sort imports within idlelib modules.
diff --git a/Lib/idlelib/README.txt b/Lib/idlelib/README.txt
index f7aad68..e52b5cd 100644
--- a/Lib/idlelib/README.txt
+++ b/Lib/idlelib/README.txt
@@ -228,4 +228,23 @@
 
 <No menu>
 Center Insert      # eEW.center_insert_event
-   
+
+  
+CODE STYLE -- Generally PEP 8.
+
+import
+------
+Put import at the top, unless there is a good reason otherwise.
+PEP 8 says to group stdlib, 3rd-party dependencies, and package imports.
+For idlelib, the groups are general stdlib, tkinter, and idlelib.
+Sort modules within each group, except that tkinter.ttk follows tkinter.
+Sort 'from idlelib import mod1' and 'from idlelib.mod2 import object'
+together by module, ignoring within module objects.
+Put 'import __main__' after other idlelib imports.
+
+Imports only needed for testing are not at the top but are put in the
+htest function def or the "if __name__ == '__main__'" clause.
+
+Within module imports like "from idlelib.mod import class" may cause
+circular imports to deadlock.  Even without this, circular imports may
+require at least one of the imports to be delayed until a function call.
diff --git a/Lib/idlelib/autocomplete.py b/Lib/idlelib/autocomplete.py
index 1200008..1e44fa5 100644
--- a/Lib/idlelib/autocomplete.py
+++ b/Lib/idlelib/autocomplete.py
@@ -4,26 +4,27 @@
 a window with all available names, for the user to select from.
 """
 import os
-import sys
 import string
+import sys
 
-from idlelib.config import idleConf
-
-# This string includes all chars that may be in an identifier
-ID_CHARS = string.ascii_letters + string.digits + "_"
-
-# These constants represent the two different types of completions
+# These constants represent the two different types of completions.
+# They must be defined here so autocomple_w can import them.
 COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1)
 
 from idlelib import autocomplete_w
+from idlelib.config import idleConf
 from idlelib.hyperparser import HyperParser
-
 import __main__
 
+# This string includes all chars that may be in an identifier.
+# TODO Update this here and elsewhere.
+ID_CHARS = string.ascii_letters + string.digits + "_"
+
 SEPS = os.sep
 if os.altsep:  # e.g. '/' on Windows...
     SEPS += os.altsep
 
+
 class AutoComplete:
 
     menudefs = [
diff --git a/Lib/idlelib/autocomplete_w.py b/Lib/idlelib/autocomplete_w.py
index 31837e0..3374c6e 100644
--- a/Lib/idlelib/autocomplete_w.py
+++ b/Lib/idlelib/autocomplete_w.py
@@ -3,8 +3,9 @@
 """
 from tkinter import *
 from tkinter.ttk import Scrollbar
-from idlelib.multicall import MC_SHIFT
+
 from idlelib.autocomplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
+from idlelib.multicall import MC_SHIFT
 
 HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
 HIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
diff --git a/Lib/idlelib/autoexpand.py b/Lib/idlelib/autoexpand.py
index 7190607..6b46bee 100644
--- a/Lib/idlelib/autoexpand.py
+++ b/Lib/idlelib/autoexpand.py
@@ -12,8 +12,8 @@
 
 This is an extension file and there is only one instance of AutoExpand.
 '''
-import string
 import re
+import string
 
 ###$ event <<expand-word>>
 ###$ win <Alt-slash>
@@ -100,7 +100,6 @@
             i = i-1
         return line[i:]
 
-
 if __name__ == '__main__':
     import unittest
     unittest.main('idlelib.idle_test.test_autoexpand', verbosity=2)
diff --git a/Lib/idlelib/browser.py b/Lib/idlelib/browser.py
index 9968333..ea05638 100644
--- a/Lib/idlelib/browser.py
+++ b/Lib/idlelib/browser.py
@@ -11,13 +11,13 @@
 """
 
 import os
-import sys
 import pyclbr
+import sys
 
-from idlelib import pyshell
-from idlelib.windows import ListedToplevel
-from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
 from idlelib.config import idleConf
+from idlelib import pyshell
+from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
+from idlelib.windows import ListedToplevel
 
 file_open = None  # Method...Item and Class...Item use this.
 # Normally pyshell.flist.open, but there is no pyshell.flist for htest.
diff --git a/Lib/idlelib/calltips.py b/Lib/idlelib/calltips.py
index 3a9b1c6..abcc142 100644
--- a/Lib/idlelib/calltips.py
+++ b/Lib/idlelib/calltips.py
@@ -5,7 +5,6 @@
 which disappear when you type a closing parenthesis.
 
 """
-import __main__
 import inspect
 import re
 import sys
@@ -14,6 +13,7 @@
 
 from idlelib import calltip_w
 from idlelib.hyperparser import HyperParser
+import __main__
 
 class CallTips:
 
diff --git a/Lib/idlelib/codecontext.py b/Lib/idlelib/codecontext.py
index 2a21a1f..f25e1b3 100644
--- a/Lib/idlelib/codecontext.py
+++ b/Lib/idlelib/codecontext.py
@@ -9,10 +9,12 @@
 not open blocks are not shown in the context hints pane.
 
 """
-import tkinter
-from tkinter.constants import TOP, LEFT, X, W, SUNKEN
 import re
 from sys import maxsize as INFINITY
+
+import tkinter
+from tkinter.constants import TOP, LEFT, X, W, SUNKEN
+
 from idlelib.config import idleConf
 
 BLOCKOPENERS = {"class", "def", "elif", "else", "except", "finally", "for",
diff --git a/Lib/idlelib/colorizer.py b/Lib/idlelib/colorizer.py
index f5dd03d..7310bb2 100644
--- a/Lib/idlelib/colorizer.py
+++ b/Lib/idlelib/colorizer.py
@@ -1,9 +1,10 @@
-import time
-import re
-import keyword
 import builtins
-from idlelib.delegator import Delegator
+import keyword
+import re
+import time
+
 from idlelib.config import idleConf
+from idlelib.delegator import Delegator
 
 DEBUG = False
 
diff --git a/Lib/idlelib/config.py b/Lib/idlelib/config.py
index d2f0b13..10fe3ba 100644
--- a/Lib/idlelib/config.py
+++ b/Lib/idlelib/config.py
@@ -18,10 +18,10 @@
 """
 # TODOs added Oct 2014, tjr
 
+from configparser import ConfigParser
 import os
 import sys
 
-from configparser import ConfigParser
 from tkinter.font import Font, nametofont
 
 class InvalidConfigType(Exception): pass
diff --git a/Lib/idlelib/configdialog.py b/Lib/idlelib/configdialog.py
index 2f361bd..fa47aaa 100644
--- a/Lib/idlelib/configdialog.py
+++ b/Lib/idlelib/configdialog.py
@@ -11,17 +11,17 @@
 """
 from tkinter import *
 from tkinter.ttk import Scrollbar
-import tkinter.messagebox as tkMessageBox
 import tkinter.colorchooser as tkColorChooser
 import tkinter.font as tkFont
+import tkinter.messagebox as tkMessageBox
 
 from idlelib.config import idleConf
-from idlelib.dynoption import DynOptionMenu
 from idlelib.config_key import GetKeysDialog
+from idlelib.dynoption import DynOptionMenu
+from idlelib import macosx
 from idlelib.query import SectionName, HelpSource
 from idlelib.tabbedpages import TabbedPageSet
 from idlelib.textview import view_text
-from idlelib import macosx
 
 class ConfigDialog(Toplevel):
 
diff --git a/Lib/idlelib/debugger.py b/Lib/idlelib/debugger.py
index ea393b1..114d0d1 100644
--- a/Lib/idlelib/debugger.py
+++ b/Lib/idlelib/debugger.py
@@ -1,10 +1,12 @@
-import os
 import bdb
+import os
+
 from tkinter import *
 from tkinter.ttk import Scrollbar
-from idlelib.windows import ListedToplevel
-from idlelib.scrolledlist import ScrolledList
+
 from idlelib import macosx
+from idlelib.scrolledlist import ScrolledList
+from idlelib.windows import ListedToplevel
 
 
 class Idb(bdb.Bdb):
diff --git a/Lib/idlelib/debugobj.py b/Lib/idlelib/debugobj.py
index c116fcd..b70b13c 100644
--- a/Lib/idlelib/debugobj.py
+++ b/Lib/idlelib/debugobj.py
@@ -8,11 +8,10 @@
 
 # XXX TO DO:
 # - for classes/modules, add "open source" to object browser
+from reprlib import Repr
 
 from idlelib.tree import TreeItem, TreeNode, ScrolledCanvas
 
-from reprlib import Repr
-
 myrepr = Repr()
 myrepr.maxstring = 100
 myrepr.maxother = 100
diff --git a/Lib/idlelib/dynoption.py b/Lib/idlelib/dynoption.py
index 962f2c3..9c6ffa4 100644
--- a/Lib/idlelib/dynoption.py
+++ b/Lib/idlelib/dynoption.py
@@ -3,6 +3,7 @@
 and setting of highlightthickness
 """
 import copy
+
 from tkinter import OptionMenu, _setit, StringVar, Button
 
 class DynOptionMenu(OptionMenu):
diff --git a/Lib/idlelib/editor.py b/Lib/idlelib/editor.py
index 7372ecf..ae475cb 100644
--- a/Lib/idlelib/editor.py
+++ b/Lib/idlelib/editor.py
@@ -6,24 +6,28 @@
 import re
 import string
 import sys
+import tokenize
+import traceback
+import webbrowser
+
 from tkinter import *
 from tkinter.ttk import Scrollbar
 import tkinter.simpledialog as tkSimpleDialog
 import tkinter.messagebox as tkMessageBox
-import traceback
-import webbrowser
 
-from idlelib.multicall import MultiCallCreator
-from idlelib import query
-from idlelib import windows
-from idlelib import search
-from idlelib import grep
-from idlelib import replace
-from idlelib import pyparse
 from idlelib.config import idleConf
-from idlelib import help_about, textview, configdialog
-from idlelib import macosx
+from idlelib import configdialog
+from idlelib import grep
 from idlelib import help
+from idlelib import help_about
+from idlelib import macosx
+from idlelib.multicall import MultiCallCreator
+from idlelib import pyparse
+from idlelib import query
+from idlelib import replace
+from idlelib import search
+from idlelib import textview
+from idlelib import windows
 
 # The default tab setting for a Text widget, in average-width characters.
 TK_TABWIDTH_DEFAULT = 8
@@ -1515,9 +1519,6 @@
             break
     return raw, effective
 
-import tokenize
-_tokenize = tokenize
-del tokenize
 
 class IndentSearcher(object):
 
@@ -1542,8 +1543,8 @@
         return self.text.get(mark, mark + " lineend+1c")
 
     def tokeneater(self, type, token, start, end, line,
-                   INDENT=_tokenize.INDENT,
-                   NAME=_tokenize.NAME,
+                   INDENT=tokenize.INDENT,
+                   NAME=tokenize.NAME,
                    OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
         if self.finished:
             pass
@@ -1554,19 +1555,19 @@
             self.finished = 1
 
     def run(self):
-        save_tabsize = _tokenize.tabsize
-        _tokenize.tabsize = self.tabwidth
+        save_tabsize = tokenize.tabsize
+        tokenize.tabsize = self.tabwidth
         try:
             try:
-                tokens = _tokenize.generate_tokens(self.readline)
+                tokens = tokenize.generate_tokens(self.readline)
                 for token in tokens:
                     self.tokeneater(*token)
-            except (_tokenize.TokenError, SyntaxError):
+            except (tokenize.TokenError, SyntaxError):
                 # since we cut off the tokenizer early, we can trigger
                 # spurious errors
                 pass
         finally:
-            _tokenize.tabsize = save_tabsize
+            tokenize.tabsize = save_tabsize
         return self.blkopenline, self.indentedline
 
 ### end autoindent code ###
diff --git a/Lib/idlelib/filelist.py b/Lib/idlelib/filelist.py
index b5af90cc..f46ad7c 100644
--- a/Lib/idlelib/filelist.py
+++ b/Lib/idlelib/filelist.py
@@ -1,4 +1,5 @@
 import os
+
 from tkinter import *
 import tkinter.messagebox as tkMessageBox
 
diff --git a/Lib/idlelib/grep.py b/Lib/idlelib/grep.py
index cfb0ea0..64ba28d 100644
--- a/Lib/idlelib/grep.py
+++ b/Lib/idlelib/grep.py
@@ -1,11 +1,14 @@
-import os
 import fnmatch
+import os
 import sys
+
 from tkinter import StringVar, BooleanVar
 from tkinter.ttk import Checkbutton
-from idlelib import searchengine
+
 from idlelib.searchbase import SearchDialogBase
-# Importing OutputWindow fails due to import loop
+from idlelib import searchengine
+
+# Importing OutputWindow here fails due to import loop
 # EditorWindow -> GrepDialop -> OutputWindow -> EditorWindow
 
 def grep(text, io=None, flist=None):
@@ -127,9 +130,9 @@
 
 
 def _grep_dialog(parent):  # htest #
-    from idlelib.pyshell import PyShellFileList
     from tkinter import Toplevel, Text, SEL, END
     from tkinter.ttk import Button
+    from idlelib.pyshell import PyShellFileList
     top = Toplevel(parent)
     top.title("Test GrepDialog")
     x, y = map(int, parent.geometry().split('+')[1:])
diff --git a/Lib/idlelib/help.py b/Lib/idlelib/help.py
index 03d6ea2..77e01a3 100644
--- a/Lib/idlelib/help.py
+++ b/Lib/idlelib/help.py
@@ -27,9 +27,11 @@
 from html.parser import HTMLParser
 from os.path import abspath, dirname, isfile, join
 from platform import python_version
+
 from tkinter import Toplevel, Frame, Text, Menu
 from tkinter.ttk import Menubutton, Scrollbar
 from tkinter import font as tkfont
+
 from idlelib.config import idleConf
 
 ## About IDLE ##
diff --git a/Lib/idlelib/help_about.py b/Lib/idlelib/help_about.py
index 54f3599..071bd3e 100644
--- a/Lib/idlelib/help_about.py
+++ b/Lib/idlelib/help_about.py
@@ -1,12 +1,14 @@
 """About Dialog for IDLE
 
 """
-
 import os
 from sys import version
+
 from tkinter import *
+
 from idlelib import textview
 
+
 class AboutDialog(Toplevel):
     """Modal about dialog for idle
 
@@ -144,6 +146,7 @@
     def Ok(self, event=None):
         self.destroy()
 
+
 if __name__ == '__main__':
     import unittest
     unittest.main('idlelib.idle_test.test_help_about', verbosity=2, exit=False)
diff --git a/Lib/idlelib/history.py b/Lib/idlelib/history.py
index 6068d4f..56f53a0 100644
--- a/Lib/idlelib/history.py
+++ b/Lib/idlelib/history.py
@@ -2,6 +2,7 @@
 
 from idlelib.config import idleConf
 
+
 class History:
     ''' Implement Idle Shell history mechanism.
 
@@ -99,6 +100,7 @@
         self.pointer = None
         self.prefix = None
 
+
 if __name__ == "__main__":
     from unittest import main
-    main('idlelib.idle_test.test_idlehistory', verbosity=2, exit=False)
+    main('idlelib.idle_test.test_history', verbosity=2, exit=False)
diff --git a/Lib/idlelib/hyperparser.py b/Lib/idlelib/hyperparser.py
index f904a39..450a709 100644
--- a/Lib/idlelib/hyperparser.py
+++ b/Lib/idlelib/hyperparser.py
@@ -4,11 +4,10 @@
 proper indentation of code.  HyperParser gives additional information on
 the structure of code.
 """
-
-import string
 from keyword import iskeyword
-from idlelib import pyparse
+import string
 
+from idlelib import pyparse
 
 # all ASCII chars that may be in an identifier
 _ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + "_")
diff --git a/Lib/idlelib/idle_test/test_iomenu.py b/Lib/idlelib/idle_test/test_iomenu.py
index f8ff112..65bf593 100644
--- a/Lib/idlelib/idle_test/test_iomenu.py
+++ b/Lib/idlelib/idle_test/test_iomenu.py
@@ -1,6 +1,7 @@
 import unittest
 import io
-from idlelib.pyshell import PseudoInputFile, PseudoOutputFile
+
+from idlelib.run import PseudoInputFile, PseudoOutputFile
 
 
 class S(str):
@@ -230,4 +231,4 @@
 
 
 if __name__ == '__main__':
-    unittest.main()
+    unittest.main(verbosity=2)
diff --git a/Lib/idlelib/macosx.py b/Lib/idlelib/macosx.py
index f9f558d..c225dd9 100644
--- a/Lib/idlelib/macosx.py
+++ b/Lib/idlelib/macosx.py
@@ -2,9 +2,10 @@
 A number of functions that enhance IDLE on Mac OSX.
 """
 from sys import platform  # Used in _init_tk_type, changed by test.
-import tkinter
 import warnings
 
+import tkinter
+
 
 ## Define functions that query the Mac graphics type.
 ## _tk_type and its initializer are private to this section.
diff --git a/Lib/idlelib/multicall.py b/Lib/idlelib/multicall.py
index 8a66cd9..b74fed4 100644
--- a/Lib/idlelib/multicall.py
+++ b/Lib/idlelib/multicall.py
@@ -28,9 +28,9 @@
    unless this conflicts with the first rule.
 Each function will be called at most once for each event.
 """
-
-import sys
 import re
+import sys
+
 import tkinter
 
 # the event type constants, which define the meaning of mc_type
diff --git a/Lib/idlelib/outwin.py b/Lib/idlelib/outwin.py
index b3bc786..f6d2915 100644
--- a/Lib/idlelib/outwin.py
+++ b/Lib/idlelib/outwin.py
@@ -1,9 +1,12 @@
-from tkinter import *
-from idlelib.editor import EditorWindow
 import re
+
+from tkinter import *
 import tkinter.messagebox as tkMessageBox
+
+from idlelib.editor import EditorWindow
 from idlelib import iomenu
 
+
 class OutputWindow(EditorWindow):
 
     """An editor window that can serve as an output file.
diff --git a/Lib/idlelib/paragraph.py b/Lib/idlelib/paragraph.py
index 0323b53..5d358ee 100644
--- a/Lib/idlelib/paragraph.py
+++ b/Lib/idlelib/paragraph.py
@@ -14,10 +14,11 @@
   spaces, they will not be considered part of the same block.
 * Fancy comments, like this bulleted list, aren't handled :-)
 """
-
 import re
+
 from idlelib.config import idleConf
 
+
 class FormatParagraph:
 
     menudefs = [
@@ -189,6 +190,7 @@
     if m is None: return ""
     return m.group(1)
 
+
 if __name__ == "__main__":
     import unittest
     unittest.main('idlelib.idle_test.test_paragraph',
diff --git a/Lib/idlelib/parenmatch.py b/Lib/idlelib/parenmatch.py
index 9586a3b..ccec708 100644
--- a/Lib/idlelib/parenmatch.py
+++ b/Lib/idlelib/parenmatch.py
@@ -4,7 +4,6 @@
 paren.  Paren here is used generically; the matching applies to
 parentheses, square brackets, and curly braces.
 """
-
 from idlelib.hyperparser import HyperParser
 from idlelib.config import idleConf
 
diff --git a/Lib/idlelib/pathbrowser.py b/Lib/idlelib/pathbrowser.py
index 966af4b..6c19508 100644
--- a/Lib/idlelib/pathbrowser.py
+++ b/Lib/idlelib/pathbrowser.py
@@ -1,10 +1,10 @@
+import importlib.machinery
 import os
 import sys
-import importlib.machinery
 
-from idlelib.tree import TreeItem
 from idlelib.browser import ClassBrowser, ModuleBrowserTreeItem
 from idlelib.pyshell import PyShellFileList
+from idlelib.tree import TreeItem
 
 
 class PathBrowser(ClassBrowser):
@@ -24,6 +24,7 @@
     def rootnode(self):
         return PathBrowserTreeItem()
 
+
 class PathBrowserTreeItem(TreeItem):
 
     def GetText(self):
@@ -36,6 +37,7 @@
             sublist.append(item)
         return sublist
 
+
 class DirBrowserTreeItem(TreeItem):
 
     def __init__(self, dir, packages=[]):
@@ -95,6 +97,7 @@
         sorted.sort()
         return sorted
 
+
 def _path_browser(parent):  # htest #
     flist = PyShellFileList(parent)
     PathBrowser(flist, _htest=True)
diff --git a/Lib/idlelib/percolator.py b/Lib/idlelib/percolator.py
index 4474f9a..d18daf0 100644
--- a/Lib/idlelib/percolator.py
+++ b/Lib/idlelib/percolator.py
@@ -1,5 +1,5 @@
-from idlelib.redirector import WidgetRedirector
 from idlelib.delegator import Delegator
+from idlelib.redirector import WidgetRedirector
 
 
 class Percolator:
diff --git a/Lib/idlelib/pyparse.py b/Lib/idlelib/pyparse.py
index 9ccbb25..6739dfd 100644
--- a/Lib/idlelib/pyparse.py
+++ b/Lib/idlelib/pyparse.py
@@ -1,6 +1,6 @@
+from collections import Mapping
 import re
 import sys
-from collections import Mapping
 
 # Reason last stmt is continued (or C_NONE if it's not).
 (C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE,
diff --git a/Lib/idlelib/pyshell.py b/Lib/idlelib/pyshell.py
index 740c72e..e1eade1 100755
--- a/Lib/idlelib/pyshell.py
+++ b/Lib/idlelib/pyshell.py
@@ -15,9 +15,13 @@
             parent=root)
     sys.exit(1)
 
+from code import InteractiveInterpreter
 import getopt
+import io
+import linecache
 import os
 import os.path
+from platform import python_version, system
 import re
 import socket
 import subprocess
@@ -25,23 +29,20 @@
 import threading
 import time
 import tokenize
+import warnings
 
-import linecache
-from code import InteractiveInterpreter
-from platform import python_version, system
-
-from idlelib import testing
-from idlelib.editor import EditorWindow, fixwordbreaks
-from idlelib.filelist import FileList
+from idlelib import testing  # bool value
 from idlelib.colorizer import ColorDelegator
-from idlelib.undo import UndoDelegator
-from idlelib.outwin import OutputWindow
 from idlelib.config import idleConf
-from idlelib.run import idle_formatwarning, PseudoInputFile, PseudoOutputFile
-from idlelib import rpc
 from idlelib import debugger
 from idlelib import debugger_r
+from idlelib.editor import EditorWindow, fixwordbreaks
+from idlelib.filelist import FileList
 from idlelib import macosx
+from idlelib.outwin import OutputWindow
+from idlelib import rpc
+from idlelib.run import idle_formatwarning, PseudoInputFile, PseudoOutputFile
+from idlelib.undo import UndoDelegator
 
 HOST = '127.0.0.1' # python execution server on localhost loopback
 PORT = 0  # someday pass in host, port for remote debug capability
@@ -51,7 +52,6 @@
 # temporarily redirect the stream to the shell window to display warnings when
 # checking user's code.
 warning_stream = sys.__stderr__  # None, at least on Windows, if no console.
-import warnings
 
 def idle_showwarning(
         message, category, filename, lineno, file=None, line=None):
diff --git a/Lib/idlelib/query.py b/Lib/idlelib/query.py
index a4584df..3b1f1e2 100644
--- a/Lib/idlelib/query.py
+++ b/Lib/idlelib/query.py
@@ -23,9 +23,10 @@
 import importlib
 import os
 from sys import executable, platform  # Platform is set for one test.
+
 from tkinter import Toplevel, StringVar, W, E, N, S
-from tkinter import filedialog
 from tkinter.ttk import Frame, Button, Entry, Label
+from tkinter import filedialog
 from tkinter.font import Font
 
 class Query(Toplevel):
diff --git a/Lib/idlelib/replace.py b/Lib/idlelib/replace.py
index 367bfc9..abd9e59 100644
--- a/Lib/idlelib/replace.py
+++ b/Lib/idlelib/replace.py
@@ -3,12 +3,12 @@
 Defines various replace related functions like replace, replace all,
 replace+find.
 """
-from tkinter import StringVar, TclError
-
-from idlelib import searchengine
-from idlelib.searchbase import SearchDialogBase
 import re
 
+from tkinter import StringVar, TclError
+
+from idlelib.searchbase import SearchDialogBase
+from idlelib import searchengine
 
 def replace(text):
     """Returns a singleton ReplaceDialog instance.The single dialog
diff --git a/Lib/idlelib/rpc.py b/Lib/idlelib/rpc.py
index 48105f2..8f57edb8 100644
--- a/Lib/idlelib/rpc.py
+++ b/Lib/idlelib/rpc.py
@@ -26,23 +26,21 @@
 accomplished in Idle.
 
 """
-
-import sys
-import os
+import builtins
+import copyreg
 import io
-import socket
+import marshal
+import os
+import pickle
+import queue
 import select
+import socket
 import socketserver
 import struct
-import pickle
+import sys
 import threading
-import queue
 import traceback
-import copyreg
 import types
-import marshal
-import builtins
-
 
 def unpickle_code(ms):
     co = marshal.loads(ms)
@@ -60,10 +58,12 @@
     p.dump(obj)
     return f.getvalue()
 
+
 class CodePickler(pickle.Pickler):
     dispatch_table = {types.CodeType: pickle_code}
     dispatch_table.update(copyreg.dispatch_table)
 
+
 BUFSIZE = 8*1024
 LOCALHOST = '127.0.0.1'
 
@@ -487,16 +487,19 @@
     # Token mix-in class
     pass
 
+
 def remoteref(obj):
     oid = id(obj)
     objecttable[oid] = obj
     return RemoteProxy(oid)
 
+
 class RemoteProxy(object):
 
     def __init__(self, oid):
         self.oid = oid
 
+
 class RPCHandler(socketserver.BaseRequestHandler, SocketIO):
 
     debugging = False
@@ -514,6 +517,7 @@
     def get_remote_proxy(self, oid):
         return RPCProxy(self, oid)
 
+
 class RPCClient(SocketIO):
 
     debugging = False
@@ -539,6 +543,7 @@
     def get_remote_proxy(self, oid):
         return RPCProxy(self, oid)
 
+
 class RPCProxy(object):
 
     __methods = None
@@ -587,6 +592,7 @@
         if not callable(attr):
             attributes[name] = 1
 
+
 class MethodProxy(object):
 
     def __init__(self, sockio, oid, name):
diff --git a/Lib/idlelib/run.py b/Lib/idlelib/run.py
index c7ee0b3..afa9744 100644
--- a/Lib/idlelib/run.py
+++ b/Lib/idlelib/run.py
@@ -2,21 +2,21 @@
 import linecache
 import queue
 import sys
-import _thread as thread
-import threading
 import time
 import traceback
-import tkinter
+import _thread as thread
+import threading
+import warnings
 
-from idlelib import calltips
-from idlelib import autocomplete
+import tkinter  # Tcl, deletions, messagebox if startup fails
 
-from idlelib import debugger_r
-from idlelib import debugobj_r
-from idlelib import stackviewer
-from idlelib import rpc
-from idlelib import iomenu
-
+from idlelib import autocomplete  # AutoComplete, fetch_encodings
+from idlelib import calltips  # CallTips
+from idlelib import debugger_r  # start_debugger
+from idlelib import debugobj_r  # remote_object_tree_item
+from idlelib import iomenu  # encoding
+from idlelib import rpc  # multiple objects
+from idlelib import stackviewer  # StackTreeItem
 import __main__
 
 for mod in ('simpledialog', 'messagebox', 'font',
@@ -27,7 +27,6 @@
 
 LOCALHOST = '127.0.0.1'
 
-import warnings
 
 def idle_formatwarning(message, category, filename, lineno, line=None):
     """Format warnings the IDLE way."""
@@ -280,6 +279,7 @@
     capture_warnings(False)
     sys.exit(0)
 
+
 class MyRPCServer(rpc.RPCServer):
 
     def handle_error(self, request, client_address):
diff --git a/Lib/idlelib/runscript.py b/Lib/idlelib/runscript.py
index 7e7524a..79d86ad 100644
--- a/Lib/idlelib/runscript.py
+++ b/Lib/idlelib/runscript.py
@@ -20,11 +20,12 @@
 import os
 import tabnanny
 import tokenize
+
 import tkinter.messagebox as tkMessageBox
-from idlelib import pyshell
 
 from idlelib.config import idleConf
 from idlelib import macosx
+from idlelib import pyshell
 
 indent_message = """Error: Inconsistent indentation detected!
 
diff --git a/Lib/idlelib/scrolledlist.py b/Lib/idlelib/scrolledlist.py
index 4799995..cc08c26 100644
--- a/Lib/idlelib/scrolledlist.py
+++ b/Lib/idlelib/scrolledlist.py
@@ -1,7 +1,9 @@
 from tkinter import *
-from idlelib import macosx
 from tkinter.ttk import Scrollbar
 
+from idlelib import macosx
+
+
 class ScrolledList:
 
     default = "(None)"
diff --git a/Lib/idlelib/search.py b/Lib/idlelib/search.py
index 508a35c..4b90659 100644
--- a/Lib/idlelib/search.py
+++ b/Lib/idlelib/search.py
@@ -24,6 +24,7 @@
     "Handle the editor edit menu item and corresponding event."
     return _setup(text).find_selection(text)
 
+
 class SearchDialog(SearchDialogBase):
 
     def create_widgets(self):
diff --git a/Lib/idlelib/searchbase.py b/Lib/idlelib/searchbase.py
index b326a1c..5f81785 100644
--- a/Lib/idlelib/searchbase.py
+++ b/Lib/idlelib/searchbase.py
@@ -3,6 +3,7 @@
 from tkinter import Toplevel, Frame
 from tkinter.ttk import Entry, Label, Button, Checkbutton, Radiobutton
 
+
 class SearchDialogBase:
     '''Create most of a 3 or 4 row, 3 column search dialog.
 
diff --git a/Lib/idlelib/searchengine.py b/Lib/idlelib/searchengine.py
index 2e3700e..253f1b0 100644
--- a/Lib/idlelib/searchengine.py
+++ b/Lib/idlelib/searchengine.py
@@ -1,5 +1,6 @@
 '''Define SearchEngine for search dialogs.'''
 import re
+
 from tkinter import StringVar, BooleanVar, TclError
 import tkinter.messagebox as tkMessageBox
 
@@ -14,6 +15,7 @@
         # This creates a cycle that persists until root is deleted.
     return root._searchengine
 
+
 class SearchEngine:
     """Handles searching a text widget for Find, Replace, and Grep."""
 
@@ -186,6 +188,7 @@
             col = len(chars) - 1
         return None
 
+
 def search_reverse(prog, chars, col):
     '''Search backwards and return an re match object or None.
 
diff --git a/Lib/idlelib/stackviewer.py b/Lib/idlelib/stackviewer.py
index c8c802c..0698def 100644
--- a/Lib/idlelib/stackviewer.py
+++ b/Lib/idlelib/stackviewer.py
@@ -1,11 +1,12 @@
-import os
-import sys
 import linecache
+import os
 import re
+import sys
+
 import tkinter as tk
 
-from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
 from idlelib.debugobj import ObjectTreeItem, make_objecttreeitem
+from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
 
 def StackBrowser(root, flist=None, tb=None, top=None):
     if top is None:
@@ -16,6 +17,7 @@
     node = TreeNode(sc.canvas, None, item)
     node.expand()
 
+
 class StackTreeItem(TreeItem):
 
     def __init__(self, flist=None, tb=None):
@@ -54,6 +56,7 @@
             sublist.append(item)
         return sublist
 
+
 class FrameTreeItem(TreeItem):
 
     def __init__(self, info, flist):
@@ -95,6 +98,7 @@
             if os.path.isfile(filename):
                 self.flist.gotofileline(filename, lineno)
 
+
 class VariablesTreeItem(ObjectTreeItem):
 
     def GetText(self):
@@ -119,6 +123,7 @@
             sublist.append(item)
         return sublist
 
+
 def _stack_viewer(parent):  # htest #
     from idlelib.pyshell import PyShellFileList
     top = tk.Toplevel(parent)
diff --git a/Lib/idlelib/statusbar.py b/Lib/idlelib/statusbar.py
index a65bfb3..8618528 100644
--- a/Lib/idlelib/statusbar.py
+++ b/Lib/idlelib/statusbar.py
@@ -1,5 +1,6 @@
 from tkinter import Frame, Label
 
+
 class MultiStatusBar(Frame):
 
     def __init__(self, master, **kw):
@@ -17,6 +18,7 @@
             label.config(width=width)
         label.config(text=text)
 
+
 def _multistatus_bar(parent):  # htest #
     from tkinter import Toplevel, Frame, Text, Button
     top = Toplevel(parent)
diff --git a/Lib/idlelib/tabbedpages.py b/Lib/idlelib/tabbedpages.py
index ed07588..4186fa2 100644
--- a/Lib/idlelib/tabbedpages.py
+++ b/Lib/idlelib/tabbedpages.py
@@ -285,6 +285,7 @@
             # placed hide it
             self.tab_set.lower()
 
+
 class TabbedPageSet(Frame):
     """A Tkinter tabbed-pane widget.
 
@@ -302,6 +303,7 @@
     remove_page() methods.
 
     """
+
     class Page(object):
         """Abstract base class for TabbedPageSet's pages.
 
@@ -467,6 +469,7 @@
 
         self._tab_set.set_selected_tab(page_name)
 
+
 def _tabbed_pages(parent):  # htest #
     top=Toplevel(parent)
     x, y = map(int, parent.geometry().split('+')[1:])
diff --git a/Lib/idlelib/textview.py b/Lib/idlelib/textview.py
index 7664524..b5c9f9b 100644
--- a/Lib/idlelib/textview.py
+++ b/Lib/idlelib/textview.py
@@ -1,11 +1,11 @@
 """Simple text browser for IDLE
 
 """
-
 from tkinter import *
 from tkinter.ttk import Scrollbar
 from tkinter.messagebox import showerror
 
+
 class TextViewer(Toplevel):
     """A simple text viewer dialog for IDLE
 
diff --git a/Lib/idlelib/tree.py b/Lib/idlelib/tree.py
index 04e0734..292ce36 100644
--- a/Lib/idlelib/tree.py
+++ b/Lib/idlelib/tree.py
@@ -15,10 +15,12 @@
 # - optimize tree redraw after expand of subnode
 
 import os
+
 from tkinter import *
 from tkinter.ttk import Scrollbar
-from idlelib import zoomheight
+
 from idlelib.config import idleConf
+from idlelib import zoomheight
 
 ICONDIR = "Icons"
 
diff --git a/Lib/idlelib/undo.py b/Lib/idlelib/undo.py
index 9f291e5..4332f10 100644
--- a/Lib/idlelib/undo.py
+++ b/Lib/idlelib/undo.py
@@ -1,5 +1,7 @@
 import string
+
 from idlelib.delegator import Delegator
+
 # tkintter import not needed because module does not create widgets,
 # although many methods operate on text widget arguments.
 
@@ -158,7 +160,6 @@
 
 
 class Command:
-
     # Base class for Undoable commands
 
     tags = None
@@ -204,7 +205,6 @@
 
 
 class InsertCommand(Command):
-
     # Undoable insert command
 
     def __init__(self, index1, chars, tags=None):
@@ -262,7 +262,6 @@
 
 
 class DeleteCommand(Command):
-
     # Undoable delete command
 
     def __init__(self, index1, index2=None):
@@ -297,8 +296,8 @@
         text.see('insert')
         ##sys.__stderr__.write("undo: %s\n" % self)
 
-class CommandSequence(Command):
 
+class CommandSequence(Command):
     # Wrapper for a sequence of undoable cmds to be undone/redone
     # as a unit
 
diff --git a/Lib/idlelib/windows.py b/Lib/idlelib/windows.py
index bc74348..a3f858a 100644
--- a/Lib/idlelib/windows.py
+++ b/Lib/idlelib/windows.py
@@ -1,5 +1,6 @@
 from tkinter import *
 
+
 class WindowList:
 
     def __init__(self):
@@ -48,6 +49,7 @@
                 t, v, tb = sys.exc_info()
                 print("warning: callback failed in WindowList", t, ":", v)
 
+
 registry = WindowList()
 
 add_windows_to_menu = registry.add_windows_to_menu
diff --git a/Lib/idlelib/zoomheight.py b/Lib/idlelib/zoomheight.py
index 0016e9d..aa4a427 100644
--- a/Lib/idlelib/zoomheight.py
+++ b/Lib/idlelib/zoomheight.py
@@ -5,6 +5,7 @@
 
 from idlelib import macosx
 
+
 class ZoomHeight:
 
     menudefs = [
@@ -20,6 +21,7 @@
         top = self.editwin.top
         zoom_height(top)
 
+
 def zoom_height(top):
     geom = top.wm_geometry()
     m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)