Strong type, weak type, and dynamic type

Source: Internet
Author: User
Tags unsupported
Unlike some rumors, python is a strong language, but it is dynamic. Strong type, dynamic type, and weak type are several different (and often obfuscated) concepts. ---------------- Typing: Strong vs. Weak, static vs. dynamicby aahz
July 15,200 3

Summary
With the advent of versions such as Python, the debate over typing has heated up again. contrary to some claims (notably from Bruce Eckel), I believe Python has strong typing, and this article explains why.

What is a "type", anyway?

Before talking about what kind of type system a language supports, we shoshould establish agreement about what a type is in the first place. My definition is that a type isMetadataAbout a chunk of memory that classifies the kind of data stored there. This classification usually implicitly specifies what kinds of operations may be stored med on the data.

Common types include primitive types (strings and numbers), container types (lists/arrays and dictionaries/hashes), and user-defined types (classes ). in python, everything is an object, and every object has a type. in other words, functions, modules, and stack frames are also types.

So what's "strong typing", then?

From my POV, strong typing prevents mixing operations between mismatched types. In order to mix types, you must use an explicit conversion. Here's a simple Python example:

>>> 1 + "1"Traceback (most recent call last):  File "
 
  ", line 1, in ?TypeError: unsupported operand type(s) for +: 'int' and 'str'>>> 1 + 12>>> "1" + "1"'11'>>> 1 + int("1")2>>> "1" + str(1)'11'
 

Conversely, weak typing means that you can mix types without an explicit conversion. Consider this example from Perl:

  DB<1> print "1"+12  DB<2> print "1".111

Note that conversion is not the same thing as coercion, IMO. coercion occurs when you have a statically-typed language and you use the Syntactic Features of the language to force the usage of one type as if it were a different type (consider the common usevoid*In C). Coercion is usually a symptom of weak typing. Conversion, otoh, creates a brand-new object of the appropriate type.

Why do some people think Python has weak typing?

Historically, "strong typing" has been associated with static typing. languages noted for strong typing include Pascal and Ada; ages noted for weak typing (most notoriously basic) had primarily dynamic typing. but the language thatOughtTo be most notorious for weak typing has static typing: C/C ++ (yes, I'm lumping them together)

It's very clear that python has only dynamic typing; any target may hold a binding to any kind of object. more than that, pythonic programming style is to use inheritance primarily for implementation; Python's name-based polymorphism means that you rarely need to inherit for interface. in fact, the primary exception to inheriting for implementation is Python exceptions, which usesissubclass()For the purpose of determining which exceptions get caught byexceptClause.

I might even go so far as to say that python's name-based polymorphism is hyperpolymorphic. and therein lies the tiny kernel of truth about Python's weak typing. people who have gotten used to Java and C ++ requiring syntactic support to declare typing often feel uncomfortable with the pythonic style of relying on run-time exceptions to get thrown when an inappropriate object is passed around und:

class Silly:    def __init__(self, data):        self.data = data    def __add__(self, other):        return str(self.data) + str(other.data)def double(a):    return a + aprint double(1)print double('x')print double([1])print double(Silly({'a':1}))print double({'a':1})
Produces
2xx[1, 1]{'a': 1}{'a': 1}Traceback (most recent call last):  File "test.py", line 14, in ?    print double({'a':1})  File "test.py", line 8, in double    return a + aTypeError: unsupported operand types for +: 'dict' and 'dict'

Bruce Eckel equates "weak typing" with "latent typing", but that's at odds with historical usage, not to mention that it confuses the two axes of strong/weak and static/dynamic.

Sidebar: Name-based Polymorphism

For those of you unfamiliar with python, here's a quick intro to name-based polymorphism. python objects have an internal dictionary that contains a string for every attribute and method. when you access an attribute or method in Python code, Python simply looks up the string in the dict. therefore, if what you want is a class that works like a file, you don't need to inherit fromfile, You just create a class that hasfileMethods that are needed.

Python also defines a bunch of special methods that get called by the appropriate syntax. For example,a+bIs equivalenta.__add__(b). There are a few places in Python's internals where it directly manipulates built-in objects, but name-based polymorphism works as you expect CT about 98% of the time.

Resources discussions of Types

Tunes: Type System
Http://cliki.tunes.org/Type%20System

Type from foldoc
Http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi? Type

Python & JAVA: Side by side comparison
Http://www.ferg.org/projects/python_java_side-by-side.html

Bruce Eckel and Python's weak typing

Artima interview: type checking and techie Control
Http://www.artima.com/intv/typing.html

Strong typing vs. Strong Testing
Http://mindview.net/WebLog/log-0025

Talk back!

Have an opinion? Be the first to post a comment about this weblog entry.

RSS Feed

If you 'd like to be notified whenever aahz adds a new entry to his weblog, subscribe to his RSS feed.

About the blogger

Aahz has been using Python since 1999. he helps people on comp. lang. python, and is one of the webmasters for www.python.org. aahz focuses on the python object model and Python threads. aahz is currently working on "valid tive Python" for Addison Wesley.

This weblog entry is copyright 2003 aahz. All rights reserved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.