The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

Views: 162,854     Votes:  2 
Tags: python   optimization   pep8  
Link: 🔍 See Original Answer on Stack Overflow 🔗

Title: Should import statements always be at the top of a module?
ID: /2020/01/19/Should-import-statements-always-be-at-the-top-of-a-module_
Created: January 19, 2020    Edited:  June 20, 2020
Upload: November 24, 2022    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false


In addition to startup performance, there is a readability argument to be made for localizing import statements. For example take python line numbers 1283 through 1296 in my current first python project:

listdata.append(['tk font version', font_version])
listdata.append(['Gtk version', str(Gtk.get_major_version())+"."+

import xml.etree.ElementTree as ET

xmltree = ET.parse('/usr/share/gnome/gnome-version.xml')
xmlroot = xmltree.getroot()
result = []
for child in xmlroot:
listdata.append(['Gnome version', result[0]+"."+result[1]+"."+
                 result[2]+" "+result[3]])

If the import statement was at the top of file I would have to scroll up a long way, or press Home, to find out what ET was. Then I would have to navigate back to line 1283 to continue reading code.

Indeed even if the import statement was at the top of the function (or class) as many would place it, paging up and back down would be required.

Displaying the Gnome version number will rarely be done so the import at top of file introduces unnecessary startup lag.

⇧ hOW TO rEMAP cAPS-LOCK TO cAPS-LOCK ON uBUNTU How to remove the GobiNet and GobiSerial driver from ubuntu 16.04  ⇩