Home > Backend Development > Python Tutorial > To Import or Not to Import at the Top: Is Early Importing More Efficient Than Deferred Importing?

To Import or Not to Import at the Top: Is Early Importing More Efficient Than Deferred Importing?

Susan Sarandon
Release: 2024-12-08 06:35:13
Original
430 people have browsed it

To Import or Not to Import at the Top: Is Early Importing More Efficient Than Deferred Importing?

Import Statements: Top or Bottom?

PEP 8 dictates that import statements reside at the top of a module, leaving some to question the efficiency of importing unused classes or functions early on. A comparison arises:

class SomeClass(object):

    def not_often_called(self):
        from datetime import datetime
        self.datetime = datetime.now()
Copy after login

versus

from datetime import datetime

class SomeClass(object):

    def not_often_called(self):
        self.datetime = datetime.now()
Copy after login

Are deferred imports more efficient than upfront ones?

Although module importing is swift, it does incur a cost. By placing imports at the module's beginning, this trivial expense is paid once. However, confining imports to within functions prolongs its runtime with each function call.

Hence, for optimal efficiency, keep imports at the forefront. Only consider deferred imports if profiling reveals a performance bottleneck.

Beyond efficiency, additional justifications for lazy imports include:

  • Optional library support: Prevent code breakage when optional libraries are absent.
  • Plugin initialization: Imports within plugin initialization files allow module loading without usage. Examples exist in Bazaar plugins utilizing bzrlib's lazy-loading mechanism.

The above is the detailed content of To Import or Not to Import at the Top: Is Early Importing More Efficient Than Deferred Importing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template