Why Lazy Import is not default in Python?

2020-07-10 06:31发布

I am trying to understand few things with respect to design.

I see a number of the code where Lazy Import features is used.By Lazy Import, I mean a facility provided by certain recipes, packages and modules which support "LazyImport" style. Those implementation in general aim to import the module only when it is used and provide some extra hooks for different things. I know there the error condition is delayed over here, but I am trying to understand why Lazy Import is not a default strategy in Python.

What could it's (other) drawbacks be which prevent it from making a general useful case. Or are there languages which use this as a default import mechanism strategy.

标签: python
3条回答
一夜七次
2楼-- · 2020-07-10 06:53

Sometimes modules do important things when they are first loaded, so it might break the program to delay import of the module. For example, if a module defines command-line flags that should be parsed when the program first starts, the module must be imported before parsing the arguments. Since Python was originally designed to do imports eagerly, it's not possible to change the default behavior now without breaking some existing programs. Also, as mentioned in some of the other answers, for long-running services it's often desirable to load everything up front before serving requests so that the first few requests are not slowed down waiting for modules to be imported.

查看更多
冷血范
3楼-- · 2020-07-10 06:58

Here's an example of lazy import in python:

def xmlfrobnicator(xmlstr):
    from lxml import etree

    # do whatever

It's not commonly used because it offers very few advantages for most programmes - once loaded, the module is loaded (unless you take steps to unload it), and it's pretty rare to have a dependency that is used so infrequently that only loading it when in use is worthwhile.

I think you may have been looking at javascript, where programmes may only run for a short time, and not use all of their features, and even if they do, background loading of modules improves user-perceived speed.

查看更多
看我几分像从前
4楼-- · 2020-07-10 07:05

Python, unlike e.g. PHP, is rarely used in a way where every request/action/... causes the whole application to be started again.
So importing everything at startup has the advantage of not having to perform imports while the application is doing something where delays are annoying.
The only advantage of local/lazy imports is that you won't have problems with circular imports.

查看更多
登录 后发表回答