Factored out _get_flattener

As I was reading through the flatten implementation, I observed that there were many repetitive calls to _pop and so I sought to refactor to make the implementation a little more regular. This refactoring extracts a function _get_flattener, which returns a callable for flattening obj, and then applies _pop to the result.

When I originally wrote this patch, there was no 'mkref' support for lists, but I've rebased the changes onto the later code which does invoke mkref on lists. One interesting thing to note is that _pop was never invoked on the result of _getref. This difference is now more stark by the (possibly incorrect) additional call to _push.

I believe this approach is cleaner and easier to comprehend and to extend.