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

629
Visualizações
How do I unload (reload) a Python module?

I have a long running Python server and would like to be able to update a service without restarting the server. What is the best way to do this?

 if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo()
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can reload a module when it has already been imported using importlib.reload() :

 from importlib import reload # Python 3.4+ import foo while True: # Do some things. if is_changed(foo): foo = reload(foo)

In Python 2, reload was a builtin. In Python 3, it was moved to the imp module. In 3.4, imp was deprecated in favor of importlib . When targeting 3 or later, reference the appropriate module when calling reload or import it.

I think this is what you want. Web servers like the Django development server use this so you can see the effects of changes to your code without restarting the server process.

To quote from the documents:

  • The Python module code is recompiled and the module-level code is re-executed, defining a new set of objects that are bound to the names in the module dictionary by reusing the loader that originally loaded the module. The init function is not called a second time.

  • As with all other objects in Python, old objects are only retrieved after their reference counts drop to zero.

  • The names in the module namespace are updated to point to any new or changed objects.

  • Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they appear, if desired.

As you noted in your question, you will have to rebuild Foo objects if the Foo class resides in the foo module.

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