Sponsored Link •
Bill Venners: In Learning Python (O'Reilly, 1999),
Mark Lutz and David Ascher introduce methods with an example,
y), that returns
x * y:
>>> def times(x, y): ... return x * y; ...The authors then give two examples of invoking the
timesmethod, one that takes two integers and one that takes a string and an integer:
>>> times(2, 4) 8 >>> times('Ni', 4) 'NiNiNiNi'When 2 and 4 are passed, the
timesmethod returns 8. When
'Ni'and 4 are passed, the
'NiNiNiNi', because the
*operator on sequences (such as strings or lists) means to repeat the sequence. The authors then explain this by saying, "Recall that
*works on both numbers and sequences; because there are no type declarations in methods, you can use
timesto multiply numbers or repeat sequences."
Doesn't the lack of type declarations on method parameters make it hard to change
code, especially in public libraries? People can define a class and overload
* to mean anything. They can then pass in an instance of their class to
times, and use the
times method in a way the method's
designer never imagined, because
* means something completely
different. If I want to change how I multiply in the
times method, I am
likely breaking that code. Is the contract of a Python method not the code of the method?
Guido van Rossum: To some extent, when you're writing a public library, it is hard to change which methods or operations you apply to your arguments. I don't think that's specific to runtime typed languages though.
What the client passes in, the contract, is more restricted in a strongly typed language, but that probably gets in the way just as often as it's helpful. It is helpful because it makes clear that there's this minimal interface that you both have to agree on. It makes it difficult, because maybe in the next library version, I would like to use more properties, but those properties aren't part of the interface I said I was committed to, so then I can't do that.
Come back Monday, February 10 for Part V of this conversation with Python creator Guido van Rossum. If you'd like to receive a brief weekly email announcing new articles at Artima.com, please subscribe to the Artima Newsletter.
If programs written in runtime typed languages like Python work fine, despite the absence of
explicit contracts known at compile time, what do you think is the real benefit of explicit contracts?
Have an opinion?
Discuss this article in the News & Ideas Forum topic,
Contracts in Python
Python.org, the Python Language Website:
Microsoft press release about their acquisition of EShops, Inc.:
Introductory Material on Python:
Python FAQ Wizard:
Guido van Rossum's home page:
Other Guido van Rossum Interviews: