How can I create update function in colab without restarting its kernel?

Asked

Viewed 33 times

1

I have my functions done outside of colab, in py files, however I would like to change the function and not need to restart the colab kernel. For this function to work in the notebook I am currently needing to restart the entire notebook, I would like to pass some parameter or something of the kind so that I can run the function, edit again and be able to use it in the current state of it.

2 answers

2

The "Reload" function of importlib can force the module to be re-executed, and then the Python process of your Kernel will have the new function.

The problem is that importlib.reload alone always works for the module (in case, your .py files) and not for the function alone -

So, if you have a file "myfile.py" and in there "def myfile(): ...", need to do these two things - I recommend leaving a draft cell near the point where you are working with this, and re-running this cell every time you change the function:

import meuarquivo  # só é necessário se "meuarquivo" não foi importado antes

from importlib import reload

reload(meuarquivo)

minhafuncao = meuarquivo.minhafuncao

Instead of the last line, you can use the import syntax as well, (but after executing the reload): from meuarquivo import minhafuncao.

If you have more than one function or constants defined in the file, the assignent in the notebook has to be made for each element you use, individually. For example: from meuarquivo import funcao1, funcao2, df_horarios

And finally, if you don’t want to do the reassignment, you can also always use the full name (Qualified name) of anything in the file you’re updating. So if at all points where you use the function on the notebook always use meuarquivo.minhafuncao instead of using the from meuarquivo import funcao, just need to make the call to Reload.

1

importlib is a great option, because it actually updates the function and can be used later, after importing its function you can use the following command:

import importlib
importlib.reload(suaFuncao)
  • 1

    The use case informed in documentation is not the recharge of functions but rather module recharge.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.