Skip to content

Instantly share code, notes, and snippets.

@cathalgarvey
Created April 10, 2014 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cathalgarvey/10382870 to your computer and use it in GitHub Desktop.
Save cathalgarvey/10382870 to your computer and use it in GitHub Desktop.
An object for recursively pruning empty containers and Nonetypes from containers or sequences.
class Prune:
'Treat like a function; call Prune.prune on any datatype to prune NoneTypes and empty Tuples/Lists/Dicts.'
_t = tuple() # Empty tuple, as "(,)" literal doesn't work.
@classmethod
def prune(self, some_data):
if isinstance(some_data, (list, tuple)):
return self.prune_sequence(some_data)
elif isinstance(some_data, dict):
return self.prune_tree(some_data)
else:
return some_data
@classmethod
def prune_tree(self, D):
'Iterate recursively through dict, building new pruned dict.'
_D = {}
for k, v in D.items():
if v in ({}, [], None, self._t):
continue
elif isinstance(v, (dict, tuple, list)):
_D[k] = self.prune(v)
else:
_D[k] = v
return _D
@classmethod
def prune_sequence(self, S):
'Append pruned sub-units of S to a new sequence of same type.'
T = type(S)
_S = []
for item in S:
if item in ({}, [], None, self._t):
continue
elif isinstance(item, (dict, tuple, list)):
_S.append(self.prune(item))
else:
_S.append(item)
return T(_S)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment