How to "reimport" an object from a Python module?

Asked

Viewed 77 times

1

I wrote a module called mymodule.py who has the function

def funcion(x):
     return x

So I imported this function into a code like

from mymodule import function

and worked normally.

Then I wanted to change the function to

def function(x):
     return 2*x

but the code continues to work as in the previous version of function, with return x. How do I reimport the object functionwithout having to restart the kernel? Do you know of any function similar to the importlib.reload() for objects in Python 3?

  • 1

    What would be "restarting the kernel" in this context? You need to change the application with it running?

  • Anderrson, I use the Jupyter Notebook. In it, for me to reimport some module I need to restart the kernel, so I want to do this reimport without needing to restart it, with it running.

2 answers

2

Before the possible solution, it is good to know: The Reload process is not fault-free because if it is certain that the variables are updated, it is not guaranteed that the old ones are removed, for example if Voce renames any, the old name may continue to exist, if Voce changes object types in class definitions, existing objects can continue with their old types. * So be careful with Reload, although sometimes it’s very convenient.

Version 3.0 to 3.3:

imp.reload(module)

Version 3.4+

importlib.reload(module)

* How did I find that out? using much of the notebook jupyter and checking several faults in the Reload process, after some research I saw that I was not alone. :-(

0

If you’re using the jupyter, just press «Shift»+«Enter» on the cell, you will see that its number in brackets will increase, this means that the function has been "relined" and is now available with the new syntax (the same goes for variable definitions or any code snippet within a cell).

Browser other questions tagged

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