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):

...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.

Comments (3)


The second example is not cute, it's one way in which Python is broken.

March 11, 2014, 11:23 a.m. #
Cute is not always a compliment.

You can even do the tree on one line using lambda:

tree = lambda: collections.defaultdict(tree)

Also, I would prefer not to abuse for loops and break that way; I’d use an islice:

_, dirnames, filenames = next(itertools.islice(os.walk("/"), 1))

March 11, 2014, 11:38 a.m. #
I'm not convinced any of these are improvements, or capture their original essence.

You apparently did not approve of my comment where I made the code much shorter:

_, dirnames, filenames = next(os.walk(path))

That’s even shorter than the original code, without the for loop abuse.

March 12, 2014, 11:27 a.m. #
But the point is the loop abuse!