Recently I’ve posted two examples[1, 2] of Python idioms alongside corresponding C# idioms. It always intrigues me to look at the same concept through different lenses, and it seems to intrigue others as well, so here’s a third installment.
Today’s example comes from a real scenario. I’ve recently added a feature to the elmcity service that enables curators to control their hubs by sending Twitter direct messages to the service. One method, GetDirectMessagesFromTwitter, calls the Twitter API and returns a list of direct messages sent to the elmcity service. Another method, GetDirectMessagesFromAzure, calls the Azure table storage API and returns a list of direct messages stored there. The difference between the two lists — if any — represents new messages to be processed.
Here’s one take on Python and C# idioms for finding the difference between two lists:
fetched_messages = GetDirectMessagesFromTwitter(); stored_messages = GetDirectMessagesFromAzure(); diff = set(fetched_messages) - set(stored_messages) return list(diff)
var fetched_messages = GetDirectMessagesFromTwitter(); var stored_messages = GetDirectMessagesFromAzure(); var diff = fetched_messages.Except( stored_messages); return diff.ToList();
I can’t decide which one I prefer. Python’s set arithmetic is mathematically pure. But C#’s noun-verb syntax is appealing too. Which do you prefer? And why?
PS: The Python example above is slightly concocted. It won’t work as shown here because I’m modeling Twitter direct messages as .NET objects. IronPython can use those objects, but the set subtraction fails because the objects returned from the two API calls aren’t directly comparable.
A real working example would add something like this:
fetched_message_sigs = [x.text+x.datetime for x in fetched_messages] stored_message_sigs = [x.text+x.datetime for x in stored_messages] diff = list(set(fetched_message_sigs) - set(stored_message_sigs))
But that’s a detail that would only obscure the side-by-side comparison I’m making here.