Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function each time I hit enter in the Python shell

I sometimes write small functions at the interactive shell.

They very rarely are correct the first time, so I spend a lot of time running the versions of my function on the same testset to verify correctness.

>>> def test_foo():
        print( foo(4) == 5 )
        print( foo(8) == 9 )
>>> def foo(x): return x + 1
>>> test_foo()
True
True

But foo may be more complicated and I may need 5 or more rewritings to get it to pass my tests, as running the suite manually is boring, I need something like this:

>>> def test_foo():
        print( foo(4) == 5 )
        print( foo(8) == 9 )
>>> :SET_ON_EXECUTION test_foo

And now each time I rewrite my foo function and send it to definition the test will be run too.

Some research

  • Searching Google gives no useful answer.
  • In the shell python -h does not tell me how to do this.
  • Neither does %quickref in 'ipython, `.
like image 496
Caridorc Avatar asked Feb 08 '23 23:02

Caridorc


2 Answers

I would strongly recommend using Jupyter notebooks (previously known as IPython) for this. It allows you to create a 'cell' containing code which you can re-execute with Ctrl-Enter key combination.

For example in your case you could put the function definition and the execution in the same cell and then easily re-execute it as you edit.

Jupyter notebook interface

In this way you can gradually build up your code, fixing and developing a single function at a time.

As you already have IPython installed you should be able to get up and running with:

$ pip install jupyter
$ jupyter notebook

It will launch in your browser. Create a new notebook by clicking 'New' in the upper-right and selecting one of the Python kernels under 'Notebooks'.

like image 56
mfitzp Avatar answered Feb 13 '23 04:02

mfitzp


You could edit your code in an editor and run your tests in a terminal using a file watcher, resulting in your tests being run every time you save the code or test files.

For information on how to run a command whenever a file changes (file watcher), see the answers on this question: https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes

like image 30
Hubert Grzeskowiak Avatar answered Feb 13 '23 03:02

Hubert Grzeskowiak