Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Duck typing
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{short description|Style of dynamic typing in object-oriented programming}} {{Type systems}} In [[computer programming]], '''duck typing''' is an application of the [[duck test]]—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an [[object (computer science)|object]] can be used for a particular purpose. With [[nominative typing]], an object is of a given type if it is declared as such (or if a type's association with the object is inferred through mechanisms such as [[object inheritance]]). With duck typing, an object is of a given type if it has all [[Method (computer programming)|methods]] and properties required by that type.<ref>{{Cite web|url=https://docs.python.org/3/glossary.html#term-duck-typing|title=Glossary β Python 3.7.1 documentation|website=docs.python.org|access-date=2018-11-08}}</ref><ref>{{Cite web|date=2020-06-28|title=Python Duck Typing - Example|url=https://techiehours.com/python/python-duck-typing/|access-date=2020-07-26|website=Techie Hours|language=en-US|archive-date=2022-03-31|archive-url=https://web.archive.org/web/20220331075920/https://techiehours.com/python/python-duck-typing/|url-status=dead}}</ref> Duck typing may be viewed as a usage-based structural equivalence between a given object and the requirements of a type. ==Examples== This simple example in [[Python (programming language)|Python]] 3 demonstrates how any object may be used in any context until it is used in a way that it does not support. <syntaxhighlight lang="python" line="1"> class Duck: def swim(self): print("Duck swimming") def fly(self): print("Duck flying") class Whale: def swim(self): print("Whale swimming") for animal in [Duck(), Whale()]: animal.swim() animal.fly() </syntaxhighlight> Output: <syntaxhighlight lang="output"> Duck swimming Duck flying Whale swimming AttributeError: 'Whale' object has no attribute 'fly' </syntaxhighlight> If it can be assumed that anything that can swim is a duck because ducks can swim, a whale could be considered a duck; however, if it is also assumed that a duck must be capable of flying, the whale will not be considered a duck. ==In statically typed languages== In some [[Type system#Static typing|statically typed]] languages such as [[Boo (programming language)|Boo]]<ref>[http://boo.codehaus.org/Duck+Typing Boo: Duck Typing]{{webarchive |url=https://web.archive.org/web/20081006075246/http://boo.codehaus.org/Duck+Typing |date=October 6, 2008 }}</ref> and [[D_(programming_language)|D]],<ref>{{cite web | url=https://forum.dlang.org/post/hf1e1h$81s$1@digitalmars.com | title=Dynamic classes and duck typing }}</ref><ref>{{cite web | url=https://stackoverflow.com/questions/16578676/duck-typing-in-d | title=Metaprogramming - duck typing in D }}</ref> class type checking can be specified to occur at runtime rather than at compile time. ==Comparison with other type systems== ===Structural type systems=== Duck typing is similar to, but distinct from, [[Structural type system|structural typing]]. Structural typing is a [[Type system#Static typing|static typing]] system that determines type compatibility and equivalence by a type's structure, whereas duck typing is [[Type system#Dynamic typing|dynamic]] and determines type compatibility by only that part of a type's structure that is accessed during [[Runtime (program lifecycle phase)|runtime]]. The [[TypeScript]],<ref>{{Cite web|url=https://www.se-radio.net/2019/10/episode-384-boris-cherny-on-typescript|title=SE Radio Episode 384: Boris Cherny on TypeScript|website=se-radio.net|access-date=2019-10-25}}</ref> [[Elm (programming language)|Elm]]<ref>{{cite web|url=http://guide.elm-lang.org/core_language.html|title=Core Language Β· An Introduction to Elm|first=Evan|last=Czaplicki|access-date=30 January 2017}}</ref> and [[Python (programming language)|Python]]<ref>{{Cite web|url=https://peps.python.org/pep-0544/|title=PEP 544 β Protocols: Structural subtyping (static duck typing)}}</ref> languages support structural typing to varying degrees. ===Protocols and interfaces=== [[Interface (object-oriented programming)|Protocols and interfaces]] provide a way to explicitly declare that some methods, operators or behaviors must be defined. If a third-party library implements a class that cannot be modified, a client cannot use an instance of it with an interface unknown to that library even if the class satisfies the interface requirements. A common solution to this problem is the [[adapter pattern]]. In contrast, with duck typing, the object would be accepted directly without the need for an adapter. ===Templates or generic types=== [[Template metaprogramming|Template]] (also called [[Generic programming|generic]]) functions or methods apply the duck test in a [[Type system#Static typing|static typing]] context; this brings all of the advantages and disadvantages of [[Type system#Static and dynamic type checking in practice|static versus dynamic type checking]]. Duck typing can also be more flexible in that only the methods actually called at runtime must be implemented, while templates require implementations of all methods that cannot be proven [[Unreachable code|unreachable]] at compile time. In languages such as Java, Scala and Objective-C, [[reflection (computer programming)|reflection]] may be employed to inspect whether objects implement methods or add necessary methods at runtime. For example, [[Java (programming language)|Java]]'s MethodHandle API can be used in this manner.<ref>{{cite web|url=https://stackoverflow.com/questions/62321273/implement-duck-typing-using-java-methodhandles|title=StackOverflow: Implement duck typing using java MethodHandles|access-date=13 June 2020}}</ref> ==See also== * [[Ad hoc polymorphism]] * [[Dynamic dispatch]] * [[Dynamic programming language]] * [[Extension method]] * [[Loose coupling]] * [[Monkey patch]] * [[Operator overloading]] ==References== {{reflist}} {{DEFAULTSORT:Duck Typing}} [[Category:Articles with example pseudocode]] [[Category:Object-oriented programming]] [[Category:Type theory]] [[Category:Articles with example Python (programming language) code]] [[Category:Ducks in popular culture]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Type systems
(
edit
)
Template:Webarchive
(
edit
)