optimization - Should Python import statements always be at the top of a module? -


pep 08 states:

imports put @ top of file, after module comments , docstrings, , before module globals , constants.

however if class/method/function importing used in rare cases, surely more efficient import when needed?

isn't this:

class someclass(object):      def not_often_called(self)         datetime import datetime         self.datetime = datetime.now() 

more efficient this?

from datetime import datetime  class someclass(object):      def not_often_called(self)         self.datetime = datetime.now() 

module importing quite fast, not instant. means that:

  • putting imports @ top of module fine, because it's trivial cost that's paid once.
  • putting imports within function cause calls function take longer.

so if care efficiency, put imports @ top. move them function if profiling shows (you did profile see best improve performance, right??)


the best reasons i've seen perform lazy imports are:

  • optional library support. if code has multiple paths use different libraries, don't break if optional library not installed.
  • in __init__.py of plugin, might imported not used. examples bazaar plugins, use bzrlib's lazy-loading framework.

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -