Duck typing
Encyclopedia
In computer programming
with object-oriented
programming language
s, duck typing is a style of dynamic typing in which an object's current set of method
s and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test
, attributed to James Whitcomb Riley
(see history below), which may be phrased as follows:
In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. It is this action of any object having the correct walk and quack methods being accepted by the function that evokes the quotation and hence the name of this form of typing.
Duck typing is aided by habitually not testing for the type of arguments in method and function bodies, relying on documentation, clear code, and testing to ensure correct use.
function calculate(a, b, c) => return (a+b)*c
example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)
print to_string example1
print to_string example2
print to_string example3
In the example, each time the
or Python
, for example, the result of the code would be:
9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
apples and oranges, apples and oranges, apples and oranges,
Thus, duck typing allows polymorphism
without inheritance
. The only requirement that function
The duck test can be seen in the following example (in Python). As far as the function
.
The Objective Caml
and Scala languages use structural type systems.
library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you have defined yourself, whereas duck typing would allow this. Again, all of an interface must be satisfied for compatibility.
, or generic
functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic type checking in general. Duck typing can also be more flexible in that only the methods actually called at run time need to be implemented, while templates require implementation of all methods that cannot be proven unreachable
at compile time.
Examples include the languages C++
and D
with templates, which developed from Ada
generics.
In essence, the problem is that, "if it walks like a duck and quacks like a duck", it could be a dragon doing a duck impersonation. You may not always want to let dragons into a pond, even if they can impersonate a duck.
Proponents of duck typing, such as Guido van Rossum
, argue that the issue is handled by testing, and the necessary knowledge of the codebase required to maintain it.
Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically typed versus statically typed programming language semantics.
made an early (2000) use of the term in a message to the comp.lang.python newsgroup
. He also highlighted misunderstanding of the literal duck test, which may indicate that the term was already in use:
allows one to declare objects of type 'dynamic' and send any message to them. At run-time the message passing will either succeed or throw an exception. The 'dynamic' type is the default for object variables and method arguments when a type has not been explicitly declared for them. This feature was inspired by Objective-C.
allows function arguments to be specified as having type any. For this sort of argument, an arbitrary object can be passed in and method calls are bound dynamically at runtime. If an object does not implement a called method, a runtime exception is thrown which can be caught and handled gracefully. In ColdFusion 8, this can be picked up as a defined event onMissingMethod rather than through an exception handler. An alternative argument type of WEB-INF.cftags.component restricts the passed argument to be a ColdFusion Component (CFC), which provides better error messages should a non-object be passed in.
provides an object-oriented extension (Common Lisp Object System, or shorter CLOS). The combination of CLOS and Lisp's dynamic typing make duck typing a common programming style in Common Lisp.
With Common Lisp one also does not need to query the types, since at runtime an error will be signaled when a function is not applicable. The error can be handled with the Condition System of Common Lisp. Methods are defined outside of classes and can also be defined for specific objects.
The usual development style of Common Lisp (by using a Lisp REPL like SLIME
) allows also the interactive repair:
This way software can be developed by extending partially working duck typed code.
, a cross between C
and Smalltalk
, allows one to declare objects of type 'id' and send any message to them, like in Smalltalk. The sender can test an object to see if it responds to a message, the object can decide at the time of the message whether it will respond to it or not, and if the sender sends a message a recipient cannot respond to, an exception is raised. Thus, duck typing is fully supported by Objective-C.
looks for method definitions in package set with bless function.
uses variable functions and variable variables to perform duck typing. Sometimes call_user_func or similar are also used.
. The Python's Glossary defines duck typing as follows:
The canonical example of duck typing in Python is file-like classes. Classes can implement some or all of the methods of
-compressed data.
The EAFP principle describes the use of exception handling
. For example instead of checking to see if some purportedly Duck-like object has a quack method (using
Advantages of this approach are that it encourages the structured handling of other classes of errors (so, for example, a mute Duck subclass could raise a "QuackException" which can be added to the wrapper without delving more deeply into the logic of the code, and it handles situations where different classes of objects might have naming collisions for incompatible members (for example, Mallard the purported medical professional might have a boolean attribute which classifies him as a "quack=True"; an attempt to perform Mallard.quack would raise a TypeError)).
In the more practical examples of classes which implement file-like behavior the use of Python's exception handling facilities is generally preferred for handling a wide variety of I/O
errors that can occur due to numerous environmental and operating system
issues that are outside of the programmer's control. Here again the "duck typing" exceptions can be caught in their own clauses alongside the OS
, I/O or other possible errors without complicated testing and error checking logic.
Simply stated: provided you can perform the job, we don't care who your parents are.
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
with object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s, duck typing is a style of dynamic typing in which an object's current set of method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
s and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test
Duck test
The duck test is a humorous term for a form of inductive reasoning. This is its usual expression:The test implies that a person can identify an unknown subject by observing that subject's habitual characteristics...
, attributed to James Whitcomb Riley
James Whitcomb Riley
James Whitcomb Riley was an American writer, poet, and best selling author. During his lifetime he was known as the Hoosier Poet and Children's Poet for his dialect works and his children's poetry respectively...
(see history below), which may be phrased as follows:
- When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. It is this action of any object having the correct walk and quack methods being accepted by the function that evokes the quotation and hence the name of this form of typing.
Duck typing is aided by habitually not testing for the type of arguments in method and function bodies, relying on documentation, clear code, and testing to ensure correct use.
Concept examples
Consider the following pseudo-code for a duck-typed language:function calculate(a, b, c) => return (a+b)*c
example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)
print to_string example1
print to_string example2
print to_string example3
In the example, each time the
calculate
function is called, objects without related inheritance may be used (numbers, lists and strings). As long as the objects support the "+" and "*" methods, the operation will succeed. If translated to RubyRuby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
or Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, for example, the result of the code would be:
9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
apples and oranges, apples and oranges, apples and oranges,
Thus, duck typing allows polymorphism
Type polymorphism
In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions...
without inheritance
Inheritance (computer science)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
. The only requirement that function
calculate
needs in its variables is having the "+" and the "*" methods.The duck test can be seen in the following example (in Python). As far as the function
in_the_forest
is concerned, the Person
object is a duck:In statically typed languages
Certain usually statically typed languages such as Boo and the version 4 release of C# have extra type annotations that instruct the compiler to arrange for type checking of classes to occur at run-time rather than compile time, and include run-time type checking code in the compiled output. Such additions allow the language to enjoy most of the benefits of duck typing with the only drawback being the need to identify and specify such dynamic classes at compile time.Structural type systems
Duck typing is similar to but distinct from structural typing. Structural typing is a static typing system that determines type compatibility and equivalence by a type's structure, whereas duck typing is dynamic and determines type compatibility by only that part of a type's structure that is accessed during run timeRuntime
In computer science, run time, run-time, runtime, or execution time is the time during which a program is running , in contrast to other phases of a program's lifecycle such as compile time, link time, load time, etc....
.
The Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...
and Scala languages use structural type systems.
Interfaces
Interfaces can provide some of the benefits of duck typing but duck typing is distinct in that no explicit interface is defined. For example, if a third party JavaJava (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you have defined yourself, whereas duck typing would allow this. Again, all of an interface must be satisfied for compatibility.
Templates or generic types
TemplateTemplate (programming)
Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one....
, or generic
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic type checking in general. Duck typing can also be more flexible in that only the methods actually called at run time need to be implemented, while templates require implementation of all methods that cannot be proven unreachable
Unreachable code
Unreachable code is a computer programming term for code in the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program....
at compile time.
Examples include the languages C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
and D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...
with templates, which developed from Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
generics.
Criticism
One issue with duck typing is that it forces the programmer to have a much wider understanding of the code he or she is working with at any given time. In a strongly and statically typed language that uses type hierarchies and parameter type checking, it's much harder to supply an unexpected object type to a class. For instance, in Python, you could easily create a class called Wine, which expects a class implementing the "press" attribute as an ingredient. However, a class called Trousers might also implement the press method. With Duck Typing, in order to prevent strange, hard-to-detect errors, the developer needs to be aware of each potential use of the method "press", even when it's conceptually unrelated to what he or she is working on.In essence, the problem is that, "if it walks like a duck and quacks like a duck", it could be a dragon doing a duck impersonation. You may not always want to let dragons into a pond, even if they can impersonate a duck.
Proponents of duck typing, such as Guido van Rossum
Guido van Rossum
Guido van Rossum is a Dutch computer programmer who is best known as the author of the Python programming language. In the Python community, Van Rossum is known as a "Benevolent Dictator For Life" , meaning that he continues to oversee the Python development process, making decisions where necessary...
, argue that the issue is handled by testing, and the necessary knowledge of the codebase required to maintain it.
Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically typed versus statically typed programming language semantics.
History
Alex MartelliAlex Martelli
Alex Martelli is an Italian computer engineer and member of the Python Software Foundation. Since early 2005, he works as "Über Tech Lead" for Google, Inc. in Mountain View, California...
made an early (2000) use of the term in a message to the comp.lang.python newsgroup
Newsgroup
A usenet newsgroup is a repository usually within the Usenet system, for messages posted from many users in different locations. The term may be confusing to some, because it is usually a discussion group. Newsgroups are technically distinct from, but functionally similar to, discussion forums on...
. He also highlighted misunderstanding of the literal duck test, which may indicate that the term was already in use:
In other words, don't check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need to play your language-games with.
In C#
In C# 4.0 the compiler and runtime collaborate to implement dynamic member lookup. Notice how parameter duck is declared dynamic in method InTheForest of class Program.In Cobra
In addition to static typing, CobraCobra (programming language from Cobra Language LLC)
Cobra is an object-oriented programming language produced by Cobra Language LLC. Cobra is designed by Chuck Esterbrook, and runs on the Microsoft .NET and Mono platforms. It is strongly influenced by Python, C#, Eiffel, Objective-C, and other programming languages. It supports both static and...
allows one to declare objects of type 'dynamic' and send any message to them. At run-time the message passing will either succeed or throw an exception. The 'dynamic' type is the default for object variables and method arguments when a type has not been explicitly declared for them. This feature was inspired by Objective-C.
In ColdFusion
The web application scripting language ColdFusionColdFusion
In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...
allows function arguments to be specified as having type any. For this sort of argument, an arbitrary object can be passed in and method calls are bound dynamically at runtime. If an object does not implement a called method, a runtime exception is thrown which can be caught and handled gracefully. In ColdFusion 8, this can be picked up as a defined event onMissingMethod rather than through an exception handler. An alternative argument type of WEB-INF.cftags.component restricts the passed argument to be a ColdFusion Component (CFC), which provides better error messages should a non-object be passed in.
In Common Lisp
Common LispCommon Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...
provides an object-oriented extension (Common Lisp Object System, or shorter CLOS). The combination of CLOS and Lisp's dynamic typing make duck typing a common programming style in Common Lisp.
With Common Lisp one also does not need to query the types, since at runtime an error will be signaled when a function is not applicable. The error can be handled with the Condition System of Common Lisp. Methods are defined outside of classes and can also be defined for specific objects.
The usual development style of Common Lisp (by using a Lisp REPL like SLIME
SLIME
SLIME, the Superior Lisp Interaction Mode for Emacs, is an Emacs mode for developing Common Lisp applications. SLIME originates in an Emacs mode called SLIM written by Eric Marsden and developed as an open-source project by Luke Gorrie and Helmut Eller. Over 100 Lisp developers have contributed...
) allows also the interactive repair:
This way software can be developed by extending partially working duck typed code.
In JavaScript
In Lua
Lua supports duck typing as part of the Metatable weak-typing system. Any reference to a table's member function is checked dynamically at run-time. If an object does not implement the requested function, a run-time error is produced. If a data member is requested but does not exist, a nil value is returned.In Objective-C
Objective-CObjective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...
, a cross between C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, allows one to declare objects of type 'id' and send any message to them, like in Smalltalk. The sender can test an object to see if it responds to a message, the object can decide at the time of the message whether it will respond to it or not, and if the sender sends a message a recipient cannot respond to, an exception is raised. Thus, duck typing is fully supported by Objective-C.
In Perl
PerlPerl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
looks for method definitions in package set with bless function.
In PHP
PHPPHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
uses variable functions and variable variables to perform duck typing. Sometimes call_user_func or similar are also used.
In Python
Duck typing is heavily used in PythonPython (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
. The Python's Glossary defines duck typing as follows:
The canonical example of duck typing in Python is file-like classes. Classes can implement some or all of the methods of
file
and can be used where file
would normally be used. For example, GzipFile
implements a file-like object for accessing gzipGzip
Gzip is any of several software applications used for file compression and decompression. The term usually refers to the GNU Project's implementation, "gzip" standing for GNU zip. It is based on the DEFLATE algorithm, which is a combination of Lempel-Ziv and Huffman coding...
-compressed data.
cStringIO
allows treating a Python string as a file. Sockets and files share many of the same methods as well. However, sockets lack the tell
method and cannot be used everywhere that GzipFile
can be used. This shows the flexibility of duck typing: a file-like object can implement only methods it is able to, and consequently it can only be used in situations where it makes sense.The EAFP principle describes the use of exception handling
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
. For example instead of checking to see if some purportedly Duck-like object has a quack method (using
if hasattr(mallard, "quack"): ...
) it's usually preferable to wrap the attempted quacking with exception handling:Advantages of this approach are that it encourages the structured handling of other classes of errors (so, for example, a mute Duck subclass could raise a "QuackException" which can be added to the wrapper without delving more deeply into the logic of the code, and it handles situations where different classes of objects might have naming collisions for incompatible members (for example, Mallard the purported medical professional might have a boolean attribute which classifies him as a "quack=True"; an attempt to perform Mallard.quack would raise a TypeError)).
In the more practical examples of classes which implement file-like behavior the use of Python's exception handling facilities is generally preferred for handling a wide variety of I/O
I/O
I/O may refer to:* Input/output, a system of communication for information processing systems* Input-output model, an economic model of flow prediction between sectors...
errors that can occur due to numerous environmental and operating system
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...
issues that are outside of the programmer's control. Here again the "duck typing" exceptions can be caught in their own clauses alongside the OS
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...
, I/O or other possible errors without complicated testing and error checking logic.
Simply stated: provided you can perform the job, we don't care who your parents are.
In PowerShell
This is the concept example from the beginning of the page.In Ruby
External links
- Duck Typing: Ruby
- How to duck type? - the psychology of static typing in Ruby
- Python documentation glossary entry on duck-typing
- Dr. Dobbs June 01 2005: "Templates and Duck Typing"
- Javascript 'typeof' limitations and duck typing
- Python from a Java perspective - Part 2 - How duck typing influences class design and design principles
- Apache Software Foundation "commons" proxy project provides DuckTyping implementation in Java