In computer science, duck typing is a term for dynamic typing typical of some programming languages, such as Smalltalk or Visual FoxPro, where a variable's value itself determines what the variable can do. It also implies that an object is interchangeable with any other object that implements the same interface, regardless of whether the objects have a related inheritance hierarchy.
The term is a reference to the "duck test"—"If it walks like a duck and quacks like a duck, it must be a duck." One can also say that the duck typing method ducks the issue of typing variables.
Dave Thomas is thought to have originated the term in the Ruby community.
The Smalltalk architects sought to achieve true polymorphism with the Smalltalk protocol proposal for abstract data types: static interfaces that existed only to guarantee a particular interface. Dynamic mechanisms used in these languages (such as genericizing the "method not found" exception handler into a catch-all lookup mechanism, parallels to which came to be called duck typing in Java and Python) would converge and employ a single reasonable syntax.
C++ templates implement a static form of Duck typing. An iterator, for example, does not inherit its methods from an Iterator base class.
Yet another approach similar to duck typing is OCaml's structural subtyping, where object types are compatible if their method signatures are compatible, regardless of their declared inheritance. This is all detected at compile time through OCaml's type inference system.
type() or isinstance(). Instead, it typically employs hasattr() tests or EAFP (Easier to Ask Forgiveness than Permission) programming.
The standard 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 gzip-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 be only used in situations where it makes sense.
Orme formalized this knowledge by creating a class that makes duck typing simple and natural for Java programmers (see "Java Does Duck Typing"). Cedric Beust later cautioned about possible dangers using duck typing in "The Perils of Duck Typing".
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Duck typing".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world