Simplifying Sofeng’s Python Recursion Example

29 08 2008

In Python recursion example to navigate tree data, Sofeng presents this solution…

def outer(data):
    class Namespace: pass
    ns = Namespace()
    ns.level = 1

    def inner(data):
        print ' ' * ns.level + data['text']
        if data['count'] > 0:
            ns.level += 1
            for kid in data['kids']:
                inner(kid)
            ns.level -= 1

    inner(data)

if __name__ == '__main__':
    outer(data)

…for traversing a dictionary of the form:

data = {'count': 2,
        'text': '1',
        'kids': [{'count': 3,
                  'text': '1.1',
                  'kids': [{'count': 1,
                            'text': '1.1.1',
                            'kids': [{'count':0,
                                      'text': '1.1.1.1',
                                      'kids': []}]},
...
}

Since his blog doesn’t seem to support code formatting in the comments, I’m repeating my comment here:

You actually don’t need the ‘count’ keys in the data dictionary, nor do you need the “if data[‘count’] > 0:” block. The code can be simplified even further by using a closure instead of the ‘Namespace’ class, eliminating the need for two (“outer” & “inner”) routines:

def traverse(data):
    print ' ' * traverse.level + data['text']
    for kid in data['kids']:
        traverse.level += 1
        traverse(kid)
        traverse.level -= 1
if __name__ == '__main__':
    traverse.level = 1
    traverse(data)
Advertisements




Python Packages via Easy Install for a Unified-Installer-built Plone

18 12 2007

Because Plone/Zope requires an older version of Python than comes out of the box with many OS’s, some people recommend installing Plone with the Unified Installer. On Unix-like systems, the Unified Installer builds Python, Zope, Plone, and some dependencies from source and keeps the whole shebang relatively segregated from the rest of the OS.

This is great until you need to install an additional Python package for a Plone product. For which of your multiple Python versions will your installer build the package? This question would be frustrating enough even if there weren’t at least five different installers for Python packages.

The installer I use, and the one I’ll write about here, is Easy Install, which comes with setuptools. Having much experience with Perl, I chose Easy Install because it’s supposedly “the closest thing to CPAN currently available for Python.” One problem with Easy Install is that it tends to install packages in the system Python site-packages directory. Here’s how to easy_install packages for the Python built by the Unified Installer:

  1. cd $ZOPE/bin
  2. wget http://peak.telecommunity.com/dist/ez_setup.py
  3. ./python ez_setup.py
  4. ./python -m easy_install $package_name

Voila! See the Easy Install docs for details about why this works.

You may also want to set up some aliases for your various Pythons.