Is there a way to continuously source a python file in interactive mode?

Viewed 74

Suppose I have file foo.py:

def foo():
 print("foo")

And I start an interactive session:

>>> import foo 
>>> foo.foo()
'foo'

Next, I add a function to the python file:

def bar():
  print("bar")

And I update my interactive session:

>>> import foo
>>> foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined

So I realize I forgot that the import is cached:

>>> from importlib import reload
>>> reload(foo)
>>> foo.bar()
'bar'

Is there an easy way to have the interactive session continuously update with any changes that accumulate in foo.py?


I had to add this for clarity, since there are a variety of ways this question can be misunderstood:

The specific purpose of this question is to be able to work in interactive mode EXACTLY the way interactive mode should be worked in, and be able to call functions that are written dynamically in another window, buffer, or context after a write to drive, WITHOUT entering reload.

In other words, I would like to eliminate unnecessary keystrokes (CTRL-R reload ENTER, for example) every time I pop back and forth between buffers.

Is there an easy way?

(it is ok if the answer is "NO")

Solutions that might create a solution, but are not "easy":

  • a pile of code
  • an interpreter-within-an-interpreter loop
  • an application
  • a novel interpreter effort
  • a new ide company

An example of an easy way something similar is done:

  • pip install --editable my-dev-module
1 Answers

As per your comments you clarified you don't need to use reload. Although, I will list all the possible options I found. For Pythn you have only 2 options:

  • use of reload(foo) (I know this is not the way you want, but exists)

  • use of importlib.reload(foo):

    import importlib
    importlib.reload(foo)
    

That's the only 2 options you have. Now, if you are using IPython, you have 2 more options:

  • use %run: %run foo.py
  • use %autoreload: the option you would be looking for is %aimport foo

For the entire explanation: https://switowski.com/blog/ipython-autoreload

If that doesn't answer your question, the the simple would be: Without using the first 2 option, it's not possible to do so

Related