Rebase Flatten PR

This is PR #3395 rebased on master. I sent this one from the ipython org, so any core dev can update it because I will be out much of today.  Or @fperez can reset #3395 to e24836f and just close this PR.