Duck typing
If it walks like a duck, and it quacks like a duck, then it must be a duck.
When duck typing is used, it's not checked if an object is of the right type, but rather whether it implements the right methods.
For example, in Python you can call the function len() on any object that implements the __len__() method, irregardless of its class.
This concept is used in dynamic languages that do not use static typing.
Example: duck typing argparse
In the following example we have a script that takes in arguments passed from the command line.
We want to separate this parsing logic from the program logic.
The run() function requires arguments to be passed, but if we want to import this function in another module without passing arguments from the command line, we can duck type the arguments passed earlier.
The arguments from argparse are loaded in a Namespace object that allows retrieval of argument arg1 using named attributes as such args.arg1.
We can duck type this Namespace object by using a namedtuple, which supports the same behavior.
It does not matter that the object type is different, as long as using args.arg1 works.
import argparse
from collections import namedtuple
def run(args):
'''
Some function that takes args object from argparse.
'''
print('Args:', args, 'Type:', type(args))
print('arg1:', args.arg1)
print('arg2:', args.arg2)
def run_with_ducktype_args():
Namespace = namedtuple('DucktypedNamespace', ['arg1', 'arg2'])
args = Namespace('Hi', 'Yolo')
run(args)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Example parser.")
parser.add_argument(
'--arg1', type=str, help="Example argument 1", required=True
)
parser.add_argument(
'--arg2', type=str, help="Example argument 2", required=False,
default='Yolo'
)
args = parser.parse_args()
# Run with args passed in from command line and with duck types args
run(args)
run_with_ducktype_args()
Outputs:
Args: Namespace(arg1="'Hi'", arg2='Yolo') Type: <class 'argparse.Namespace'>
arg1: 'Hi'
arg2: Yolo
Args: DucktypedNamespace(arg1='Hi', arg2='Yolo') Type: <class '__main__.DucktypedNamespace'>
arg1: Hi
arg2: Yolo