1

I created the following file.py

def function():
  print('Hello')

I import and call this function:

>>> from file import function
>>> function
<function function at 0x0000022BF425FB70>
>>> function()
Hello

Now I changed function to print "Hello world" instead of "Hello" and reload file again:

>>> from file import function
>>> function
<function function at 0x0000022BF425FB70>
>>> function()
Hello
>>> import inspect
>>> inspect.getsource(function)
"def function():\n\tprint('Hello world')\n"

What confuses me is that the new function is actually reloaded (which we can see from function's source code in the last line) but it still prints "Hello". How is it possible? Also function pointer didn't change even if the source code of the function did.

Edit: I think it is not duplicate with this question. I'm not asking how to reload function. I'm asking how come that source code is changed after reloading and Python still calls old version of the function.

Petar
  • 23
  • 6
  • 1
    Once you import it, it's always going to be the version you imported, even if you change it afterwards. You can use the `reload` function in the `importlib` library. – iamchoosinganame May 31 '19 at 16:31
  • 2
    Possible duplicate of [How do I unload (reload) a Python module?](https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module) – rdas May 31 '19 at 16:32
  • @iamchoosinganame But the source code is changed, it is not now the same function. – Petar May 31 '19 at 16:33
  • 1
    That's true, but it's not how python works. Once you have imported a module you can only import the new version using ```importlib.reload`` Someone else may be able to explain the reasoning behind this. You can also start a new python session and then when you import you will get the new version. – iamchoosinganame May 31 '19 at 16:35
  • @rdas I edited the question trying to explain that it is not a duplicated question. – Petar May 31 '19 at 16:48
  • `inspect.getsource()` looks at the file on disk, whether or not that version of the file on disk gave rise to the function currently in memory. Notice that the `function` object shows an id of 0x0000022BF425FB70 both before and after - that's not conclusive proof (ids can be reused for objects with disjoint lifetimes), but it's evidence that you didn't actually reload anything. – jasonharper May 31 '19 at 16:48
  • @Petar I think it's already been explained in the comments why this is happening and the underlying cause is explained in the question marked as duplicate. – rdas May 31 '19 at 16:49
  • @hasonharper That's the answer to my question I was looking for. You can move it from comments to answer if you want. – Petar May 31 '19 at 16:54

0 Answers0