|
In computer programming, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class. The name of the concept refers to the duck test, attributed to James Whitcomb Riley[citation needed], which may be phrased as follows: Programming redirects here. ...
In computer science, a type system defines how a programming language classifies values and expressions into types, how it can manipulate those types and how they interact. ...
In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods, static methods, or factory methods) or with an object (called instance methods). ...
The duck test is a specific form of inductive reasoning whereby one can infer the nature of an unknown based upon its outwardly visible traits. ...
Honorary statue of James Whitcomb Riley on courthouse lawn in Greenfield, Indiana James Whitcomb Riley (Greenfield, Indiana October 7, 1849 â July 22, 1916), American writer and poet called the Hoosier poet and Americas Childrens Poet made a start writing newspaper verse in Hoosier dialect for the Indianapolis Journal...
- If it walks like a duck and quacks like a duck, I would call it 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. Concept example
Consider the following pseudo-code for a duck typed language: function calculate(a, b, c) => return (a+b)*c a = calculate (1, 2, 3) b = calculate ([1, 2, 3], [4, 5, 6], 2) c = calculate ('apples ', 'and oranges, ', 3) print to_string a print to_string b print to_string c 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 Ruby or Python, for example, the result of the code would be: Ruby is a reflective, dynamic, object-oriented programming language. ...
Python is a general-purpose, high-level programming language. ...
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 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 object is a duck: The Greek meaning of the words poly and morph together imply that a single entity can take on multiple forms. In the field of computer science, there are two fundamentally different types of polymorphism; subtype polymorphism, and parametric polymorphism. ...
This article or section does not cite any references or sources. ...
class Duck: def quack(self): print "Quaaaaaack !" def feathers(self): print "The duck has white and gray feathers." class Person: def quack(self): print "The person imitates a duck." def feathers(self): print "The person takes a feather from the ground and shows it." def in_the_forest(duck): duck.quack() duck.feathers() def game(): donald = Duck() john = Person() in_the_forest(donald) in_the_forest(john) Comparison with other type systems Comparison with structural type systems Duck typing is similar to but distinct from structural typing. Structural typing determines type compatibility and equivalence by a type's structure, whereas duck typing determines type compatibility only by that part of a type's structure that is accessed. The Objective Caml programming language uses a structural type system. A structural type system is a major class of type system, in which type compatibility and equivalence are determined by the types structure, and not through explicit declarations. ...
Objective Caml (OCaml) 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. ...
Comparison with 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 Java library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you've defined yourself. Duck typing would allow this. An interface defines the communication boundary between two entities, such as a piece of software, a hardware device, or a user. ...
Comparison with templates or generic types Template functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic typing 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. In computer programming, templates are a feature of the C++ programming language that allow code to be written without consideration of the data type with which it will eventually be used. ...
In computer science, a type system defines how a programming language classifies values and expressions into types, how it can manipulate those types and how they interact. ...
In computer science, a type system defines how a programming language classifies values and expressions into types, how it can manipulate those types and how they interact. ...
// In computer programming, unreachable code, or dead code, is code that exists in the source code of a program but can never be executed. ...
Examples include the language C++ with templates, Java generics, and various others.
Criticism An often cited criticism is this: - 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 coder 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.
With type checking and hierarchical type declarations, all wine ingredients would be subclasses of WineIngredient or something like that, negating the problem. - 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.
In practice, the issue is equivalent to not mixing dissimilar objects for duck-typing and is handled almost transparently as part of the knowledge of the codebase required to maintain it.[citation needed] Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically (late binding) typed versus statically typed programming language semantics. In computer science, binding is associating objects and implementations with names in programming language so that those objects and implementations can be accessed by the names. ...
A counter argument to name space issues is that context can be just as important to understand source code as it is in natural communications. A reference to thisMerlot.press is clearly different than a references to mySlacks.press() or that_window[some_button].press(). In any sufficiently rich natural language there are terms which can only be understood in context, classic examples including: "Time flies like an arrow; fruit flies like a banana." and "Polish these shoes and I'll give you some Polish sausage."
History Alex Martelli 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. Alex Martelli is a member of the Python Software Foundation and works, as of 2006, as Ãber Tech Lead for Google, Inc. ...
A newsgroup is a repository usually within the Usenet system, for messages posted from many users at different locations. ...
- 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.
Implementations In Python Duck typing is heavily used in Python. The Python Tutorial's Glossary defines duck typing as follows: Python is a general-purpose, high-level programming language. ...
Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using 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. gzip is a software application used for file compression. ...
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 if hasattr(mallard, "quack"): ...) it's usually preferable to wrap the attempted quacking with exception handling (try: mallard.quack() except (AttributeError, TypeError): print >> sys.stderr "mallard can't quack()"). 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). Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ...
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. An operating system (OS) is a software that manages computer resources and provides programmers with an interface used to access those resources. ...
In Ruby Duck typing is a fundamental part of Ruby coding. The "pickaxe book" (Programming Ruby), written by Dave Thomas and Andrew Hunt, has a more complete description of duck typing, explaining its perils and benefits, as does an article called The Perils of Duck Typing, by Cedric Beust. Ruby is a reflective, dynamic, object-oriented programming language. ...
Programming Ruby is a book about Ruby programming language by David Thomas and Andrew Hunt, authors of The Pragmatic Programmers. ...
Dave Thomas is a computer programmer and author/editor. ...
Andy Hunt (sometimes credited as Andrew Hunt) is a writer of books on software development. ...
In ColdFusion The web application scripting language ColdFusion 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. This article or section does not adequately cite its references or sources. ...
In Smalltalk The object-oriented programming language Smalltalk does not have type declarations for variables or method arguments and therefore naturally supports duck typing. Classes implementing the same protocol normally belong to the same inheritance hierarchy, but this is not required. For other uses, see Small talk. ...
In Objective-C Objective-C, a cross between C and Smalltalk, allows one to declare objects of type 'id' and send any message to them, like 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. Objective-C, often referred to as ObjC or more seldomly as Objective C or Obj-C, is an object oriented programming language implemented as an extension to C. It is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard, and is the primary language...
In Perl Perl's runtime method call mechanism naturally supports duck typing. For other uses, see Perl (disambiguation). ...
In Boo Boo has a native duck type that raises runtime errors if an invalid method or property is called.
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
by the semantic web W3Cs Semantic Web logo The Semantic Web is an evolving extension of the World Wide Web in which web content can be expressed not only in natural language, but also in a format that can be read and used by software agents, thus permitting them to find, share and...
|