title: filter a variable such that its repr can be parsed by literal_eval
body: <p>I would like to <em>filter</em> a variable (i.e. remove invalid content) in order for its string representation to be parsable by <code>ast.literal_eval</code>. So basically a <code>filter_literal</code> function that guaranties the below assertion for any <code>obj</code>:</p>
  
  <pre><code>safe_obj = filter_literal(obj)
  assert ast.literal_eval(repr(safe_obj))==safe_obj
  </code></pre>
  
  <p>I came up with the following function but I am interested if there is a better approach or, otherwise, if I did anything wrong:</p>
  
  <pre><code>_literal_types = set([type(None),bool,int,float,long,complex])
  def filter_literal(obj, default=None):
      """ return given `obj` with only "literal" types
  
      The output can be safely converted to string and evaluated using 
      `ast.literal_eval`::
  
          import ast
          safe_obj = filter_literal(obj)
          assert ast.literal_eval(repr(obj))==safe_obj
  
      literal types are strings, number, tuples, lists, dicts, booleans and None
  
      non-literal content are replaced by `default`
      """
      obj_type = type(obj)
      if obj_type in _literal_types:
          return obj
      elif isinstance(obj,dict):
          return dict((k,filter_literal(v,default=default)) for k,v in obj.iteritems())
      elif isinstance(obj,list):
          return [filter_literal(v,default=default) for v in obj]
      elif isinstance(obj,tuple):
          return tuple([filter_literal(v,default=default) for v in obj])
      else:
          return default
  </code></pre>