Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
How do I use importlib.LazyLoader?

In my module, I have a couple of functions that depend on an external module with a long startup time. How do I use LazyLoader? If I have

import veggies

or

import veggies.brussels.sprouts

or

from veggies.brussels import sprouts

how would I replace those statements to use LazyLoader such that the execution of the contents of the module are postponed until needed?

It is not immediately obvious from the documentation how to use it. There is no example, and nullege code search only comes up with the unit test included with Python itself.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The original issue has some code that seems to to a full import lazily:

The following files imports two modules lazily:

import sys
import importlib.util

def lazy(fullname):
  try:
    return sys.modules[fullname]
  except KeyError:
    spec = importlib.util.find_spec(fullname)
    module = importlib.util.module_from_spec(spec)
    loader = importlib.util.LazyLoader(spec.loader)
    # Make module with proper locking and get it inserted into sys.modules.
    loader.exec_module(module)
    return module

os = lazy("os")
myown = lazy("myown")

print(os.name)
myown.test()

To test, I used the following in myown.py.

print("Executed myown.")
def test():
  print("OK")

That worked nicely (Python 3.8a0).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda