This issue depends and follows-up on #27891, consistently grouping and sorting imports in idlelib files.
PEP 8 (also) says 'all imports are put at the top of the file', though the 'consistency hobgloblin' rule allows for exceptions. Possible reasons include making circular imports work, delaying side-effects, and significantly reducing initial import time of the containing module. All are rare.
Idlelib currently has numerous exceptions, only a few of which have a documented reason. The others might have a good reason, but may be holdovers from when 'import at top' was absent or not observed. I propose to at least document the exceptions by putting comments at the top, in their sort location among other idlelib imports. Examples:
# from idlelib import module # in EditorWindow
# from idlelib.other import SomeClass # in EditorWindow
Doing this will make it possible to see at a glance all the idlelib imports in a module.
I will remove at least one redundant delayed import and move some when I am sure there is no reason not to. I may ask original authors as to their reason for placing imports where they did.
Moving 'import X' from a function is easy and safe. Moving an import from a class requires deleting 'self.' from all references, so is not safe without extra care. At least for EditorWindow, I may leave this to when editing the class anyway.
|