Skip to content

Beauty in code

I was building a list of media resources (eg. photos, videos) when I found myself writing the following code to sort that very list:

[code lang="python"] getdatetime = itemgetter('datetime') media.sort(key=getdatetime, reverse=True) [/code]

It’s not rocket science or anything new but this time I thought the above code lying beneath the expression “code beautiness” (for the record: itemgetter sits in the operator module and media is a list of dictionaries).

So, what’s your example of code beautiness? What python idioms do you find beautiful and maybe “superior” than equivalent in another language?

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • Facebook
  • Twitter
  • Google Bookmarks
  • FriendFeed
  • Google Buzz
  • HackerNews
  • Posterous
  • Reddit
  • Slashdot
  • Tumblr
  • http://deelan.com deelan

    This is a oneliner I wrote time ago to extract the most recent datetime given a list of stories and their published datetime.

    date_last_updated = max([story.date_published for story in stories])

    date_last_updated is then used to populate the updated field of a Atom feed.

    Now that I think about it, this could be improved to use a generation expression when used with a recent version of Python.

  • C8E

    from future import braces

  • http://cavedoni.com/ Antonio Cavedoni

    I must say I’m quite fond of list comprehensions myself, although my vote goes to a little-known feature of Python’s unicode implementation; you can actually call unicode codepoints by name, thus: u”N{INTERROBANG}”.

  • Jeff McNeil

    I wrote an mapper class recently that interacts with an LDAP server, and I did it like so:

    name = property(LDAPMapper.getAttribute(“cn”, str))

    The LDAPMapper.getAttribute method was then a closure of sorts:

    def getAttribute(attr, dataType):
       def inner_get(self):
          return ldapObject.ldap_search(..attr..)
       return inner_get
    

    That type of thing to me really exposes the beauty of a language like Python. Closure, first-class functions, properties, all in one system. The best part of the whole equation? I can easily subclass LDAPMapper as an account object or something of the sort and retrieve an LDAP name simply by accessing the ‘name’ parameter.

  • http://www.oluyede.org/blog/ Lawrence

    @Antonio: that’s a nice feature indeed.

    @Jeff: Cool trick! I honestly don’t use closures a lot but when it comes down to them they’re simply powerful. The whole decoration thingy is built upon closures. I think, now that you mentioned them, the basics of Python are one of its most powerful trump cards. The builtin-types, the fact that all-is-an-object and so on simply speed up our productivity but there are cases in which Python style simply excels ;-) (That’s not a comparison with other languages, don’t want to start a useless flame war)