Search code examples
pythonpython-2.7python-2.6rundeck

Python 2.6 compatibility for rundeckrun


I'm new to Python and struggling a bit with a piece of code. I am using rundeckrun which is an open source python client for the Rundeck API. There is one bit of code in the client that seems to be locked to python 2.7+ and I really need to get it to work on Python 2.6. I've tried searching but don't even really know what this construct is called so hard to find the 2.6 equivalent for it.

node_attr_keys = (
        'name',
        'hostname',
        'username',
        'description',
        'osArch',
        'osFamily',
        'osName',
        'editUrl',
        'remoteUrl',
    )

    data = {k: getattr(self, k)
            for k in node_attr_keys if getattr(self, k, None) is not None}

The specific error is:

File "/usr/lib/python2.6/site-packages/rundeckrun-0.1.11-py2.6.egg/rundeck/client.py", line 21, in from .api import RundeckApiTolerant, RundeckApi, RundeckNode File "/usr/lib/python2.6/site-packages/rundeckrun-0.1.11-py2.6.egg/rundeck/api.py", line 135 for k in node_attr_keys if getattr(self, k, None) is not None} ^ SyntaxError: invalid syntax


Solution

  • As Kevin points out, this is a dictionary comprehension.

    In Python 2.6, you can write it as a generator expression yielding a list of tuples (key/value pairs) and pass that to the dict constructor:

    data = dict((k, getattr(self, k))
                 for k in node_attr_keys if getattr(self, k, None) is not None)