cleanup logic moved upstream

cf https://github.com/ipython/ipython/pull/7172/files

closes #37