Sobes.tech
Junior — Middle

Can you explain the concept of duck typing in Python?

sobes.tech AI

Answer from AI

The concept of duck typing in Python is a programming style where the type of an object is determined by its behavior (methods and properties), rather than its explicit class.

The phrase "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck" reflects this idea.

For example, a function can accept any object that supports the write() method, regardless of its class:

def write_hello(file_like):
    file_like.write('Hello')

class File:
    def write(self, text):
        print(f'Writing to file: {text}')

class Logger:
    def write(self, text):
        print(f'Logging: {text}')

write_hello(File())   # Writing to file: Hello
write_hello(Logger()) # Logging: Hello

Thus, the interface of the object is more important than its specific type.