March 11th 2014

Two aesthetically pleasing Python snippets

The following Python tree structure recently resurfaced. I find it rare to see functional or recursive techniques expressed so succinctly in Python:

def tree():
    return collections.defaultdict(tree)

Another construction I am quite fond of is:

for _, dirnames, filenames in os.walk(path):
    break

...which leaves dirnames and filenames in the current scope, containing the immediate subdirectories and files of the specified path.

Perhaps a little too cute, but appealing in its own way.




You can subscribe to new posts via email or RSS.