Re: Type Hinting vs Type Checking and Preconditions

2006-03-10 Thread Florian Diesch
Tom Bradford [EMAIL PROTECTED] writes:

 Let me first say that I'm sure that this subject has come up before,
 and so forgive me for beating a dead horse.  Secondly, let me say that
 Python's strength is its dynamic nature, and I don't believe that it
 should ever require a precondition scaffolding. With that said, I do
 believe that something like type hinting would be beneficial to the
 Python community, both for tool enablement and for disambiguous
 programming.

 Here is what I mean.  The following function, though conventionally
 indicating that it will perform a multiplication, will yield standard
 Python behaviors if a string value is passed to it:

 def multiplyByTwo(value):
 return value * 2

 Passing 14 to it will return 28, whereas passing 14 to it will return
 1414.  Granted, we know and accept that this is Python's behavior
 when you multiply two values, but because we don't (and shouldn't have
 to) know the inner workings of a function, we don't know that the types
 of the values that we pass into it may adversly affect that results
 that it yields.

 Now, on the other hand, if we were to introduce a purely optional type
 hint to the function prototype, such as follows:

 def multiplyByTwo(value:int):
 return value * 2

 The python interpreter could do the work of casting the incoming
 parameter to an int (if it is not already) before it is multipled,
 resulting in the desired result or a typecasting error otherwise.
 Furthermore, it could do it more efficiently than a developer having to
 put conditional code at the beginning of traditionally typecasting
 functions.

What's the advantage? Instead of multiplication may not do what I want
with some classes you got casting to int may not do what I want
with some classes. 
Passing a float now returns a much more counterintuitive result than 
passing a string in the old function.
And it's not working anymore with classes which you can not cast to int 
but implement multiplication.

In any case you have to document what exactly your function is doing and
the user has to read this documentation.



   Florian
-- 
Emacs doesn't crash!  It contains very little C, so there's very
little reason to have it crash. [Pascal Bourguignon in gnu.emacs.help]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-09 Thread Tom Bradford
I don't use isinstance() and type() at all, nor am I testing the type
of all variables being passed into function.  What I'm arguing for here
is a semantic safety mechanism that is neither required, nor imposed.
Ultimately what it looks like what I'm proposing is a syntactic
shorthand for the adapt() proposal.  Which, if other developers have
called for, makes my need not so far fetched.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread msoulier
 It's actually something that has been being considered for Python 3.0
 for a long time.

I will never understand why we can't just leave a good language alone,
and instead keep trying to make it everything for all people. If I want
strong typing, I'll use Java or C++. And don't tell me to just not use
it, because the more that's added to the core language, the harder it
becomes to inherit code, the ease of which being something that Python
is supposed to stand for.

Mike Soulier

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread msoulier
 It's also important to note that while Guido did spend a lot of time
 thinking about optional type markups (and this caused a LOT of hand
 wringing in the Python community, the general consensus in the end was
 that there was no real benefit from it. (I got the impression that a
 lot of the push was from Java/C++ people that didn't really understand
 what dynamic languages are about, and wanted to make Python more like
 Java/C++. Just my impression though).

It's very comforting to hear this. Perl has already added optional
type-checking, and personally, I just shook my head and asked why?. I
came to the Python community because I was sick of Perl, and not happy
with Java, so I find myself resistent to attempts to make Python more
like either, as I'd like to leave those worlds behind.

The only compelling thing about Perl was the CPAN, and the cheeseshop
is looking better every day.

The major compelling thing about Java for me is ease of distribution,
and Python is getting better in that respect as well. 

Mike Soulier

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Tom Bradford
Really what we're talking about here is weak typing in the form of
optional type hinting performed on a function by function basis.  As an
option, what it would do is allow an author to semantically 'hint' to
the interpreter that a function is expecting a certain type, and
perform any implicit conversion if the passed type is not what was
expected, thus translating to a semantically expected result.

It is my feeling that this doesn't represent a sea-change in the way
Python does things, and it's certainly *not* the way things are done in
Java or C++, as both of those languages are strongly typed, wherein you
can't even pass a parameter if it isn't of the expected type, or a
subclass thereof.

The fact is, that with a system such as this, you could just 'not use
it', and none would be the wiser, as it's an authorship extension
rather than a calling extension.  What I was suggesting is that nothing
change other than function/method prototypes, and that everything,
everwhere, at all times continues to be represented as scalars.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Scott David Daniels
Tom Bradford wrote:
 Really what we're talking about here is weak typing in the form of
 optional type hinting performed on a function by function basis
Not what most of the world calls weak typing.

 It is my feeling that this doesn't represent a sea-change in the way
 Python does things, and it's certainly *not* the way things are done in
 Java or C++, as both of those languages are strongly typed, wherein you
 can't even pass a parameter if it isn't of the expected type, or a
 subclass thereof.
But I would call both of those languages weakly typed (and Python 
strongly typed).
Any _correct_ type system must have contra-variant typing on results and
co-variant typing on values.

Java's type system breaks because it has decided to have arrays (which
are both in and out, therefore pinned as to type) obey the subtype
relationship of the elements of that array.

So:
  array of truck-driver

is a subtype of:
  array of driver

and a procedure:

 procedure stores(driver[] arr, driver gus)
 arr[1] = gus

Will type check as type-correct when passed a taxi-cab driver.

I suspect such problems can be found in C++ as well, but I never
hunted very hard.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Jay Parlar

On Mar 8, 2006, at 7:20 AM, Tom Bradford wrote:

 Really what we're talking about here is weak typing in the form of
 optional type hinting performed on a function by function basis.  As an
 option, what it would do is allow an author to semantically 'hint' to
 the interpreter that a function is expecting a certain type, and
 perform any implicit conversion if the passed type is not what was
 expected, thus translating to a semantically expected result.


So how would that system deal with this?

class A(object):
 def foo(self):
 print bar

class B(object):
 def foo(self):
 print bar

def typedfunction(x : A):
 x.foo()

b = B()
typedfunction(b) #Your system would probably consider this an error


This is an example of why type checking/hinting is no good, as it would 
break duck typing.

  In terms of their definitions, A and B have nothing in common (ie. B 
is not a subclass of A), yet I should be able to use instances of 
either one, whenever the method 'foo' is expected. Type hinting would 
completely break that. This again is why I point you in the direction 
of PEP 246.


 The fact is, that with a system such as this, you could just 'not use
 it', and none would be the wiser, as it's an authorship extension
 rather than a calling extension.  What I was suggesting is that nothing
 change other than function/method prototypes, and that everything,
 everwhere, at all times continues to be represented as scalars.

The problem is when someone decides to use this option, and releases a 
library with it. Now everyone who wants to use this library is forced 
to use this type hinting. It would create a divide in available Python 
code. (Of course, adaption would result in the same issue, but I 
*think* more people would be willing to use adaption, as it doesn't 
break duck typing).

Jay P.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Tom Bradford
This type of hinting would only break type ducking in-so-much as a
function that leveraged that hinting would be looking specifically for
an instance of a particular type, which would be absolutely no
different than a developer performing the type check manually and
throwing it out if the type were invalid.  It would otherwise just be a
lot of tedious and repetitive work for the developer.

The fact is, as valuable as type ducking is, it has drawbacks in its
ambiguousness, that are especially harmful to large systems that are
being developed with many hands in the pot.  And no, people who use a
library that leverages this type of hinting are most certainly no more
effected by it than they would be by the methods performing the check
manually.

As the feature is optional, if you want to allow a method that allows
for type ducking, you would write it in exactly the same way you write
it now, and nobody would be harmed in the process.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Diez B. Roggisch
Tom Bradford wrote:

 This type of hinting would only break type ducking in-so-much as a
 function that leveraged that hinting would be looking specifically for
 an instance of a particular type, which would be absolutely no
 different than a developer performing the type check manually and
 throwing it out if the type were invalid.  It would otherwise just be a
 lot of tedious and repetitive work for the developer.

The thing with duck-typing is that exactly this kind of type-checking is
_not_ what the developer is supposed to do. Doing so breaks duck-typing
anyway, regardless of syntactic sugaring or not.

Adding such a feature would immediately start people creating code that for
example requires a list where an iterable would suffice - and thus eating
from the usability of python in general.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Jay Parlar

On Mar 8, 2006, at 8:43 AM, Tom Bradford wrote:


 This type of hinting would only break type ducking in-so-much as a
 function that leveraged that hinting would be looking specifically for
 an instance of a particular type, which would be absolutely no
 different than a developer performing the type check manually and
 throwing it out if the type were invalid.  It would otherwise just be a
 lot of tedious and repetitive work for the developer.


Wow, I *really* hope that you're not writing functions that check the 
types of the incoming arguments. It's generally accepted that using 
isinstance() and type() in your code are evil things to do. There 
are very few places where it's appropriate to use them.

If you're using them a lot, then I suspect you're relatively new to 
Python, and are programming with a Java/C++ mindset. We'll have to do 
what we can to get you out of that :)

Jay P.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Paul Boddie
Tom Bradford skrev:
 Really what we're talking about here is weak typing in the form of

Careful with the terminology! Weak typing is something else entirely.

 optional type hinting performed on a function by function basis.  As an
 option, what it would do is allow an author to semantically 'hint' to
 the interpreter that a function is expecting a certain type, and
 perform any implicit conversion if the passed type is not what was
 expected, thus translating to a semantically expected result.

But is it adaptation or some weaker form of that concept, where x :
int just means that you call the int function on x to coerce it
(with an exception raised if that doesn't work), or is it more of a
type-checking system, where you call isinstance(x, int) and raise an
exception if that test returns false?

 It is my feeling that this doesn't represent a sea-change in the way
 Python does things, and it's certainly *not* the way things are done in
 Java or C++, as both of those languages are strongly typed, wherein you
 can't even pass a parameter if it isn't of the expected type, or a
 subclass thereof.

Careful with the terminology, again! That calling a function with the
wrong type of argument ultimately leads to a run-time exception is
actually a sign that Python also has strong typing - it just doesn't
enforce particular argument types when actually calling a function or
method (but typically instead when looking up attributes and methods on
objects). Certainly, explicit type-checking (the second case above) is
different from how Python currently does things (except for a few
low-level calls), whereas some form of coercion is not the same as how
Python currently behaves, since passing an object of some
previously-unknown numeric type into a function which performs
multiplication wouldn't result in the conversion of that object into an
int or float, for example.

 The fact is, that with a system such as this, you could just 'not use
 it', and none would be the wiser, as it's an authorship extension
 rather than a calling extension.  What I was suggesting is that nothing
 change other than function/method prototypes, and that everything,
 everwhere, at all times continues to be represented as scalars.

I don't follow the scalars reference - sounds like Perl terminology to
me - but whilst x : int might be convenient notation for either
type-checking or coercion/adaptation, the problem would soon arise
where paranoid developers add such notation to their code in order to
insist that only types that they can think of be used with their APIs.
The consequence would be arbitrary limits on extensibility - you'd
actually have to update code to work with new or
previously-unconsidered kinds of objects - and with this, you'd soon be
the wiser about usage of the feature in question.

As C++ has shown, when designing exotic notations to describe types,
you end up with a language in itself to do that job; at which point you
might arguably be better served by either writing your type
declarations in Python rather than starting with an insufficient
mini-language which grows into a monster or, as I'd rather like to
imagine, employing alternative approaches to deal with program
analysis.

Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-08 Thread Alex Martelli
Jay Parlar [EMAIL PROTECTED] wrote:

 class A(object):
  def foo(self):
  print bar
 
 class B(object):
  def foo(self):
  print bar
 
 def typedfunction(x : A):
  x.foo()
 
 b = B()
 typedfunction(b) #Your system would probably consider this an error
 
 
 This is an example of why type checking/hinting is no good, as it would
 break duck typing.
 
   In terms of their definitions, A and B have nothing in common (ie. B
 is not a subclass of A), yet I should be able to use instances of 
 either one, whenever the method 'foo' is expected. Type hinting would
 completely break that. This again is why I point you in the direction
 of PEP 246.

Indeed, as 246's paladin, my favorite interpretation of that x: A
would be as equivalent to:

def sanefunction(_x):
x = adapt(_x, A)
x.foo()

So the code you give would raise a CantAdaptError, but only because no
adapter has been registered from B to A -- easily fixed non-invasively
e.g. by registering a DuckAdapter, basically to assert that homonimy IS
all right between these classes.

The reason I like the adaptation requirement (rather than explicit
ducktyping being always in force by default) is to avoid the homonimy
problem, a classic issue with large system -- imagine the following
pieces all being independently defined...:


class Lottery(object):
def draw(self): ...

class Artist(object):
def draw(self): ...

...

def runLotteryWithPortraitAsPrize(lottery, artist):
winner = lottery.draw()
portrait = museum.add(artist.draw())
ceremony('Award Prizes', winner, portrtait)

...

runLotteryWithPortraitAsPrize(Artist(), Lottery())


Oops -- draw means completely different and unrelated things in
different semantic domains, ducktyping doesn't work well here, and we're
placing (a photo of) the winner in the museum (presumably a web photo
gallery;-) and awarding the winner to the portrait, what a mess...!-)


OK, not a realistic usecase;-), but method homonimy may indeed happen,
and in large enough systems it may be a cause of some rare but
hard-to-find bugs -- unittests don't nail them, because they're more in
the nature of system integration problems (until the mistaken call,
everything's hunky dory). Without adaptation -- if your only alternative
was type-testing of some kind -- the inflexibility in gluing together
disparately designed frameworks would probably be too high a price to
pay, and you'd go for ducktyping and take your lumps. But adaptation
(could I but convince Guido about it...!) lets you have most of the
flexibility back (and then some, because you can easily adjust for name
differences too;-) AND still make such problems easy to find (since
they'll raise an exception when they occur).

The nature of what exactly is a protocol (what we adapt to) is quite a
secondary issue -- be it a mere interface, a type loosely standing for a
host of semantics implications, an interface+DbC+pragmatics, whatever,
being able to request adaptation (rather than merely checking
compliance, isinstance for types, etc) is STILL a huge gain.  Ah well...


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Tom Bradford
Let me first say that I'm sure that this subject has come up before,
and so forgive me for beating a dead horse.  Secondly, let me say that
Python's strength is its dynamic nature, and I don't believe that it
should ever require a precondition scaffolding. With that said, I do
believe that something like type hinting would be beneficial to the
Python community, both for tool enablement and for disambiguous
programming.

Here is what I mean.  The following function, though conventionally
indicating that it will perform a multiplication, will yield standard
Python behaviors if a string value is passed to it:

def multiplyByTwo(value):
return value * 2

Passing 14 to it will return 28, whereas passing 14 to it will return
1414.  Granted, we know and accept that this is Python's behavior
when you multiply two values, but because we don't (and shouldn't have
to) know the inner workings of a function, we don't know that the types
of the values that we pass into it may adversly affect that results
that it yields.

Now, on the other hand, if we were to introduce a purely optional type
hint to the function prototype, such as follows:

def multiplyByTwo(value:int):
return value * 2

The python interpreter could do the work of casting the incoming
parameter to an int (if it is not already) before it is multipled,
resulting in the desired result or a typecasting error otherwise.
Furthermore, it could do it more efficiently than a developer having to
put conditional code at the beginning of traditionally typecasting
functions.

All of this wouldn't require changes to the calling code, and would be
a purely optional feature of the function declaration, one that as far
as I can tell would be backward compatible both with Python's standard
operating behavior, and it's overall grammar.  This hinting would also
apply to derived class names.  Functions like the one first
demonstrated would continue to operate as normal.

The additional benefit of this type hinting mechanism is that tools
like Komodo would be able to perform a close-to-java like amount of
code analysis and completion, even though Python would continue to be
just as dynamic as it had always been, refining Python's productivity
benefits even moreso.

This could also be extended into the realm of return types, but that
might imply imposing typing in calling code, which is why I do not
propose it as part of a type hinting system, as I believe calling code
should remain unaffected by the introduction of such a system.

The next question is how do you represent lists, maps and tuples in
this system?  would it be something like this?  myList:[]   And if so,
do we further allow for typing hinting within the contents of the list
such as myList:[int]?  There would be no harm in allowing a parameter
that is a list, map, or tuple to remain in a parameter list without
type hinting, even while other parameters retain hints.

It wouldn't be hard to prototype something like this using Jython.

Thoughts?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread bearophileHUGS
You can look at this, its API looks very well thought out to me:
http://oakwinter.com/code/typecheck/

 Now, on the other hand, if we were to introduce a purely optional type
 hint to the function prototype, such as follows:
 def multiplyByTwo(value:int): return value * 2

I don't think Python will have something like this...

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Delaney, Timothy (Tim)
[EMAIL PROTECTED] wrote:

 You can look at this, its API looks very well thought out to me:
 http://oakwinter.com/code/typecheck/
 
 Now, on the other hand, if we were to introduce a purely optional
 type hint to the function prototype, such as follows:
 def multiplyByTwo(value:int): return value * 2
 
 I don't think Python will have something like this...

It's actually something that has been being considered for Python 3.0
for a long time.

Search for `python optional static typing` for discussions - the first
two links from Google are blog entries by Guido from a year ago (there's
also a third one linked from PEP 3000).

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Tom Bradford
Thanks for the info...  Kinda comforting that Guido's syntactic ideas
were somewhat similar to my own.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread bearophileHUGS
Delaney, Timothy (Tim):
 Search for `python optional static typing` for discussions - the first
 two links from Google are blog entries by Guido from a year ago (there's
 also a third one linked from PEP 3000).

I am sorry. Yes, I have read those posts about a year ago, and I
remember most of them, but I can remember that the syntax was discussed
a lot... Nothing real has come out of those discussions, I think. We'll
see.
I like the typecheck API, it's not perfect but it's not bad (and can
probably be improved still, removing some parts, changing some names,
adding some things, etc.) and it allows most of the things suggested by
Guido, plus other things, without the need to change the language
syntax at all. Can't such annotations be used by the interpreter (and
by Psyco) to produce much faster code? I remember that for Guido the
purpose of optional types wasn't much for speed, but for other purposes
(like to build very large and complex systems, as Zope), but using it
for speed purposes in smaller programs too can be cute :-)

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Jay Parlar

On Mar 7, 2006, at 1:32 PM, Tom Bradford wrote:

 Let me first say that I'm sure that this subject has come up before,
 and so forgive me for beating a dead horse.  Secondly, let me say that
 Python's strength is its dynamic nature, and I don't believe that it
 should ever require a precondition scaffolding. With that said, I do
 believe that something like type hinting would be beneficial to the
 Python community, both for tool enablement and for disambiguous
 programming.

 [snip]
 Thoughts?

You may want to look at the various adapt ideas that have come along 
(prompted by Alex Martelli's http://www.python.org/peps/pep-0246.html). 
The two dominant implementations of this idea are PJE's PyProtocols, 
and Zope.Interfaces. I've used PyProtocols with great success in the 
past.

The basic problem with type hinting is that it totally breaks duck 
typing, which is one of the reasons Python's dynamic nature is so 
powerful.

Just because a function expects a list object, I should not be 
prevented from passing in my own custom object that supports the 
necessary parts of the list protocol. This is where adaption makes its 
mark, as it is more about supported interfaces on an object than about 
actual types.

It's also important to note that while Guido did spend a lot of time 
thinking about optional type markups (and this caused a LOT of hand 
wringing in the Python community, the general consensus in the end was 
that there was no real benefit from it. (I got the impression that a 
lot of the push was from Java/C++ people that didn't really understand 
what dynamic languages are about, and wanted to make Python more like 
Java/C++. Just my impression though).

And in case you're thinking that maybe we could get some performance 
gains out of adding optional types, you should check out Brett Cannon's 
Master's thesis. In it, he actually added some typing markup to Python, 
and the end result was almost no gain.

HOWEVER: If you feel this is something you still want to have a go at , 
PLEASE try it, and let the community know what your results were. It's 
making me sad that there's a lot of talk these days about how unwilling 
the Python community is to hear new ideas.

And if you do decide to go forward with it, you should look at the 2.5 
branch of the CPython code, as the new AST is supposed to make it 
*much* easier to experiment with changes to the language.

Good luck!

Jay P.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Roy Smith
In article [EMAIL PROTECTED],
 Tom Bradford [EMAIL PROTECTED] wrote:

 Here is what I mean.  The following function, though conventionally
 indicating that it will perform a multiplication, will yield standard
 Python behaviors if a string value is passed to it:
 
 def multiplyByTwo(value):
 return value * 2
 
 Passing 14 to it will return 28, whereas passing 14 to it will return
 1414.  Granted, we know and accept that this is Python's behavior
 when you multiply two values, but because we don't (and shouldn't have
 to) know the inner workings of a function, we don't know that the types
 of the values that we pass into it may adversly affect that results
 that it yields.

The question is, what is the function *supposed to do*?  Without knowing 
what it is *supposed to do*, it is impossible to say for sure whether 
returning 1414 is correct or not.  Consider two different functions:

def multiplyByTwo_v1(value):
Returns the argument multiplied by 2.  If the argument is a
   string representation of an integer, another string is returned
   which is the string representation of that integer multiplied
   by 2.

return value * 2

def multiplyByTwo_v2(value):
Returns the argument multiplied by 2.

return value * 2

The first one should return 28 when passed 14.  If it returns 1414, 
it's broken.  I know this seems rather silly and pedantic, but it's an 
important point.

I was once working on a project which historically didn't have any unit 
tests.  We had a function called something like isValidIP in the library 
which returned True or False depending on whether its (string) argument was 
a valid IP address.

I wrote some unit tests and it failed on a corner case like 
255.255.255.255 (or maybe it was 0.0.0.0).  Turns out, the original 
author was using it in some special situation where 255.255.255.255 wasn't 
valid for his purposes.  We got down to, OK, *you* document what the 
function is supposed to do, and *I'll* write a unit test which proves it 
does what the documentation says.  You would think that would be easy, but 
it never got done because we couldn't get everybody to agree on what the 
function was supposed to do.

It was being used in production code.  I would have thought it would bother 
people that we were using a function without knowing what it was supposed 
to do, but what really bothered people more was that we had a unit test 
that was failing.  And the solution was to back out unit test.  Sometimes 
politics trumps technology.

PS, as far as I know, that project is now dead, but for other reasons far 
worse than one underspecified function :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Paul Boddie
Roy Smith wrote:
 In article [EMAIL PROTECTED],
  Tom Bradford [EMAIL PROTECTED] wrote:
 
  def multiplyByTwo(value):
  return value * 2

[...]

 The question is, what is the function *supposed to do*?  Without knowing
 what it is *supposed to do*, it is impossible to say for sure whether
 returning 1414 is correct or not.

Indeed. And I don't think arithmetic-based examples are really very
good at bringing out the supposed benefits of type declarations or are
very illustrative when reasoning about type systems, mostly because
everyone assumes the behaviour of the various operators without
considering that in general the behaviour is arbitrary. In other words,
people look at expressions like a * b and say oh yes, numbers being
multiplied together producing more numbers without thinking that a
might be an instance of Snake and b might be an instance of
Reptile and the Snake.__mul__ method (or perhaps the
Reptile.__rmul__ method) might produce a range of different things
that aren't trivially deduced.

  Consider two different functions:

 def multiplyByTwo_v1(value):
 Returns the argument multiplied by 2.  If the argument is a
string representation of an integer, another string is returned
which is the string representation of that integer multiplied
by 2.
 
 return value * 2

 def multiplyByTwo_v2(value):
 Returns the argument multiplied by 2.
 
 return value * 2

 The first one should return 28 when passed 14.  If it returns 1414,
 it's broken.  I know this seems rather silly and pedantic, but it's an
 important point.

I've done some work on this kind of thing which actually specialises
functions/methods and produces something resembling that quoted above,
and I believe that various other works produce similar specialisations
when reasoning about the behaviour of Python programs. Specifically,
you'd write the first version like this:

def multiplyByTwo_v1(value):
if isinstance(value, int): return int.__mul__(value, 2)
elif isinstance(value, string): return string.__mul__(value, 2)
else: raise RuntimeError

Really, you'd want to avoid having a single specialisation, having
separate ones for each incoming type, although that might be hard to
arrange in every case.

Paul

P.S. Have a look here for some simple (and now quite dated) examples:

http://www.boddie.org.uk/python/analysis.html

Specifically, here:

http://www.boddie.org.uk/python/analysis-summaries.html
(A good test of CSS standards compliance if nothing else!)

I'll hopefully make a new release at some point in the near future
which tries to do a better job at deducing the various types and
invocation targets.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Donn Cave
In article [EMAIL PROTECTED],
 Delaney, Timothy (Tim) [EMAIL PROTECTED] wrote:

 [EMAIL PROTECTED] wrote:
 
  You can look at this, its API looks very well thought out to me:
  http://oakwinter.com/code/typecheck/
  
  Now, on the other hand, if we were to introduce a purely optional
  type hint to the function prototype, such as follows:
  def multiplyByTwo(value:int): return value * 2
  
  I don't think Python will have something like this...
 
 It's actually something that has been being considered for Python 3.0
 for a long time.
 
 Search for `python optional static typing` for discussions - the first
 two links from Google are blog entries by Guido from a year ago (there's
 also a third one linked from PEP 3000).

But surely, never with the proposed semantics (quoted to
match [non]attribution), with automatic conversion of
14 to 14  --

  The python interpreter could do the work of casting the incoming
  parameter to an int (if it is not already) before it is multipled,
  resulting in the desired result or a typecasting error otherwise.
  Furthermore, it could do it more efficiently than a developer having to
  put conditional code at the beginning of traditionally typecasting
  functions.

I know awk works a bit like that, maybe Perl? but it's
surely way out of place in Python.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list