Manipulating Python os.walk Recursion

The os.walk function in Python is a powerful function. It generates the file names and sub-directory names in a directory tree by walking the tree. For each directory in the tree, it yields a 3-tuple (dirpath, dirnames, filenames).

It is not well-known that you can modify dirnames in the body of the os.walk() loop to manipulate the recursion!

I’ve seen programmers avoid using os.walk(), and hack their own version of it using recursive calls to os.listdir(), with various path manipulations in the process. It was rare that the programmer doing this was not familiar with os.walk(). More often than not, the reason was that the programmer wanted more control over the recursion. Unfortunately, if the programmer was aware that this can be done with os.walk(), she would probably use it and save time and sweat!

This specific feature is well documented in the Python os.walk docs. Seeing how under-used it is, I wanted to highlight it here, hoping it will serve someone out there 🙂 .

Continue Reading…

Escaping Shortcodes In WordPress Posts

By Sunday, October 26, 2014 0 , , Permalink 0

WordPress shortcodes are an easy way to embed dynamic content in WordPress posts. But sometimes I want to write about using shortcodes. To display the verbatim shortcode text in a post, without having WordPress parse it, it must be escaped.

Escaping a shortcode is easy. Just double the enclosing square brackets.

For instance, to display [gallery] in a post, write [[gallery]].

For short codes with start and end tags, only double the first and last brackets: [[shortcode]...[/shortcode]].

It worths noting that currently the escaping will occur only if the shortcode is active. Escaping a disabled shortcode will result a doubling brackets in the output: [[fakeshortcode]] remains [[fakeshortcode]]

This is true for WordPress 4.0, but is recognized as a bug. So if it’s fixed sometime in the future, and the above example contains a single bracket – let me know in the comments so I can fix this 🙂 .