How to run a function every time I press Enter in the Python shell

I sometimes write small functions in an interactive shell.

They are rarely correct for the first time, so I spend a lot of time running versions of my function on the same set of tests to check the correctness.

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

But it foocan be more complicated, and I may need 5 or more rewrites to make it pass my tests, since running the package 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 every time I rewrite my function fooand send it to the definition, the test will also run.

Some research

  • A Google search does not provide any useful answer.
  • The shell python -hdoes not say how to do this.
  • %quickref 'ipython, `.
+4
3

Jupyter notebooks ( IPython). "", , Ctrl-Enter.

, , .

Jupyter Laptop Interface

, , .

IPython, :

$ pip install jupyter
$ jupyter notebook

. , "" Python "".

+3

ipython, whatever.py, , , ipython ipython whatever.py.

Python ~/.ipython/ipy_user_conf.py:

~/.ipython ipy_user_conf.py. python, IPython, , - , , , , IPython .. api- IPython, IPython.ipapi.get() "API IPython", IPython.

ipythonrc :

, IPython , (-rcfile) ipythonrc. , IPython, IPYTHONDIR, . rcfiles ( ).

: Python .

execfile : execute the python file specified by the command execfile(filename). Name expansion is performed by the given names. Therefore, if you need some additional bizarre mood that does not fit into any of the above “canned” options, you can simply put it in a separate python file and execute it.

+2
source

Source: https://habr.com/ru/post/1624936/


All Articles