THE PYTHONIC DUCK

“If it looks like a duck and quacks like a duck, it’s a duck”. Didn’t get anything? Worry not! I was as lost as you are right now after reading this statement about Duck Typing.

So, it all started from a thought that how should I check whether an object is a list or not(in Python)?

Then I googled it and found this on stackoverflow. I urge you to read all the answers and comments. Here, I read an answer and got to know about Duck Typing in Python.

This is a really nice example of Duck typing –

class Person:
    def help(self):
        print("Heeeelp!")

class Duck:
    def help(self):
        print("Quaaaaaack!")

class SomethingElse:
    pass

def InTheForest(x):
    x.help()

donald = Duck()
john = Person()
who = SomethingElse()

for thing in [donald, john, who]:
    try:
        InTheForest(thing)
    except AttributeError:
        print 'Meeowww!'

you can read about Duck Typing more here and here.

So Basically, don’t check for the type of a list, just see if it acts like a list.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s