Duck typing and Python

I am a fan of Python, the programming language. Unfortunately, I did not have the time or the opportunity to use it as much as I would have liked.

One of the concept I have become to liked is Duck Typing. A good visual representation would be this simple sentence from James Whitcomb Riley.

If it walks like a duck and quacks like a duck, I would call it a duck.

Baby duck

Python uses duck typing extensively. There is no type check for method arguments and return values. If the function you are calling is expecting something that walks and quacks, it will call those methods appropriately and it will work. No matter if it is a duck or a baby pretending to be a duck, as long as it have those expected methods, properties or members, it will go through.

Today, I have been reading some interviews with Guido van Rossum, the Python author. In Contracts in Python, he talks about the implicit contract between the method user and the method creator. He argues that strongly-typed languages like Java or C#, interfaces are often used as contracts but that they get in the way as much as they help.

After digesting the whole thing, I have to agree with him.

I am currently working on projects using Coldfusion, C#, Java and Javascript. Coldfusion supports duck typing with the “any” type and the onMissingMethod event handler. I have been pleased to use it recently for my unit tests.

I have to come realize how much finger typing, work and code goes into type handling with C# and Java. There is a cost for it that put some weight onto maintenance. The more code you have, the more complicated it becomes to maintain and that includes code for type handling. I am not saying that there is no advantage to using a strongly-typed language, but that there is an alternative that shows many promises.

Post a Comment

Your email is never published nor shared. Required fields are marked *

CAPTCHA image