Not really a "Vim answer", but writing a unit test and running the unit test(s) for the current file is probably the best way to do this.
Specifically for Python you can use doctests:
import datetime
def seconds_to_text(seconds):
"""Convert number of seconds to a textual representation.
>>> seconds_to_text(42)
'0:00:42'
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
"""
return str(datetime.timedelta(seconds=seconds))
if __name__ == '__main__':
import doctest
doctest.testmod()
And then just use :!python %
to run this file.
Or if you don't want to modify the Python files, you can use:
:!python -m doctest %
Or as a more convenient mapping:
augroup python_test
autocmd!
autocmd Filetype python nnoremap <Leader>t :execute ':!python -m doctest %'<CR>
augroup end
If you only want to run the current function, you can use something like:
if __name__ == '__main__':
import doctest, sys
if len(sys.argv) < 2:
doctest.testmod()
else:
for f in sys.argv[1:]:
doctest.run_docstring_examples(globals()[f], globals())
And then use :!python % seconds_to_text
; a useful mapping might be something like:
fun! TestFunction()
" Find function under cursor
let l:save = winsaveview()
normal [[
let l:fun = substitute(getline('.'), 'def \(\w*\)(.*', '\1', '')
execute ':!python % ' . l:fun
call winrestview(l:save)
endfun
augroup python_test
autocmd!
autocmd Filetype python nnoremap <Leader>t :call TestFunction()<CR>
augroup end
Which will run the tests for the current function. Typically you shouldn't really need this though, since typically unit tests are be fast enough to not notice any meaningful difference between running just one vs. running all tests for a single file.