Skip to content

Comment on Ask YC: Best practice for Python module imports?parent

Comments

PEP 8 has an opinion on everything ;)

The best reason to do them at the top of a module, at least to me, is so you know where all the imports are. The only reason I'd ever put them in functions is to avoid circular import issues.

There's really no need to use comments; reading the module should be enough to figure out what the grouping is. My only convention is sticking all the global imports in one line at the top (PEP be damned) and grouping stuff from there.

  import os, sys, datetime, xmlrpclib
  from django.http import Htt404, HttpResponseRedirect
  from django.core import serializers
  from tstumbler.util import slice_it, parse_date, flatten
Edit: it is also non-trivial from a performance point of view to have a module import every time a function is called...
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.