Ask YC: Best practice for Python module imports?

https://news.ycombinator.com/item?id=657528
by skullsplitter • 17 years ago
16 18 17 years ago

Im torn between two general module import styles. The import-everything-at-the-top approach where the beginning of each python file/module imports every module potentially needed later in the file OR the import-as-needed approach.

I know what I dont like; a file starting w/ 20+ import lines, that just seems ugly and java-y (no-flame, just sayin) to me. OTOH, the as-needed-approach seems perhaps a little too, uhm, disorganized? Although Id guess Im probably more partial to that approach.

This is a pretty minor stylistic issue but I havent settled on one approach and I'd like some feedback to come to some conclusion once and for all.

For example,

import foo import baz import bar import quux import django.foo # etc

vs.

import sys

def some_os_thing(): import os print os.getcwd()

def some_http_thing(): import urllib print urllib.urlopen('http://...').read()

Related Stories

Loading related stories...

Source preview

news.ycombinator.com