Question

this is a line from within Wagtail (Django variant CMS with very cool UI). The issue is it's written for Python 2.7 and I am using Python 2.6 with Django + FastCGI on shared hosting.

I've already changed a previous syntax error as spotted by mhlester but can't figure this one out:

>>> for attr in json_attrs
  File "<stdin>", line 1
    for attr in json_attrs
                          ^
SyntaxError: invalid syntax

the original code:

 if use_json: # Return a json response
        if search_results:
            search_results_json = []
            for result in search_results:
                result_specific = result.specific

                search_results_json.append({
                    attr: getattr(result_specific, attr)
                    for attr in json_attrs
                    if hasattr(result_specific, attr)
                })

any help please?

Était-ce utile?

La solution

There are no dictionary comprehensions in < Python 2.7. Instead you should pass a list of tuples to the dict() builtin.

dict((attr, getattr(result_specific, attr)) for attr in json_attrs if hasattr(result_specific, attr))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top