python philosophical question - strong vs duck typing

Ben Finney ben+python at benfinney.id.au
Tue Jan 3 17:28:05 EST 2012


Sean Wolfe <ether.joe at gmail.com> writes:

> Hello everybody, I'm a happy pythonista newly subscribed to the group.

Welcome!

> I have a theoretical / philosophical question regarding strong vs duck
> typing in Python. Let's say we wanted to type strongly in Python

There may be an unstated assumption there, and your wording confuses me.

Are you aware that Python has strong typing *and* duck typing,
simultaneously?

Every Python object is strongly-typed: they know exactly what type they
are, what operations are permitted with objects of other types, and
won't pretend to be a different type. (So an object of, e.g., type
‘int’, won't allow addition of itself with an object of type ‘str’.)

“Strongly-typed” is one end of a spectrum whose opposite end is
“weakly-typed”. Weakly-typed objects are in languages like e.g. PHP,
where an integer object can be added to a string object.

Every Python object allows duck typing: its operations are available to
any code that wants to use that functionality, regardless of what type
the client may assume it's working with. (This allows an object of,
e.g., type ‘StringIO’, which has no relationship to the ‘file’ type, to
be used by functions expecting a file object.)

What do you mean to convey by “strong vs. duck typing”?

> and were willing to compromise our code to the extent necessary, eg
> not changing variable types or casting or whatever. Let's say there
> was a methodology in Python to declare variable types.

Python does not have variables in the sense of languages like C; rather,
Python has references bound to objects. A reference (e.g. a name, or a
list index, etc.) never has a type. An object always has a type.

You may be thinking of “static typing” (identifiers have types, and
won't allow themselves to refer to an object of a different type),
versus “dynamic typing” (identifiers are ignorant of types – this is
what you have in Python).

> What I am driving at is, if we are coding in python but looking for
> more performance, what if we had an option to 1) restrict ourselves
> somewhat by using strong typing to 2) make it easy to compile or
> convert down to C++ and thereby gain more performance.

I would need to know what you mean instead of “strong typing”, because
Python already has that.

-- 
 \        “If we ruin the Earth, there is no place else to go. This is |
  `\    not a disposable world, and we are not yet able to re-engineer |
_o__)                      other planets.” —Carl Sagan, _Cosmos_, 1980 |
Ben Finney



More information about the Python-list mailing list