Home >Backend Development >Python Tutorial >To Import or Not to Import at the Top: Is Early Importing More Efficient Than Deferred Importing?
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()
versus
from datetime import datetime class SomeClass(object): def not_often_called(self): self.datetime = datetime.now()
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:
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!