Re: checking if a list is empty

2011-05-22 Thread Ian

On 12/05/2011 04:51, Chris Angelico wrote:

On Thu, May 12, 2011 at 7:02 AM, Ianhobso...@gmail.com  wrote:

In the real world  lists of zero items do not exist.
You don't go shopping with a shopping list of zero items.

Actually, yes you do. You maintain your shopping list between trips;
whenever you need something, you put it on the list immediately. Then
when you go shopping, you just take the list with you (if you're
lucky, you don't need to move or copy it at all, you just get another
reference to it). Once you're done, you empty the list - you now have
a shopping list with zero items (until you get home and realize you
forgot something).

Chris Angelico

He He.

I didn't claim an empty list was not useful!   If you maintain it 
between trips, then

yes, you arrive back with an empty list.

Ian



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


Re: checking if a list is empty

2011-05-22 Thread Thomas Rachel

Am 11.05.2011 23:02 schrieb Ian:


On 11/05/2011 20:13, Hans Georg Schaathun wrote:

 Lists do not have truth values in the
application domain, and therefore truth values in the
implementation domain is complicated.


Exactly. Its just a convention. If it exists, its true, if if doesn't
its false.


Right. And not only that: Python objects resp. classes not claiming to 
have a truth value (__nonzero__), but a length (__len__) are judged by 
that concerning their truth value: iff the length is 0, their truth 
value is False.



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


Re: checking if a list is empty

2011-05-21 Thread John J Lee
Gregory Ewing greg.ew...@canterbury.ac.nz writes:

 Hans Georg Schaathun wrote:
  0 is a number as real and existent as any other,
 one would think that the empty list is also as real and existent as
 any other list.

 0 does have some special properties, though, such as
 being the additive identity and not having a multiplicative
 inverse. Adding falseness as another special property isn't
 too much of a stretch and turns out to be useful.

 Likewise, it's useful to treat empty containers as having
 a similar special property, since they're often a base or
 terminating case in algorithms.

 It's especially useful in a dynamic language where any
 additional operations such as finding the length or
 comparing with zero has a run-time cost.

 Yes, you have to learn it, but it's a small thing to
 learn with a considerable payoff.

(apologies if somebody already bikeshedded this argument in this thread)

In the absence of an explicit interface declaration (have any standards
emerged for that in Python 3, BTW?), the use of len() does give you some
information about the interface, which sometimes makes it easier to
change the function.

I'm sure you fully understand this, but I'll spell it out.  Consider
this function:

def xyzzy(x):
if x:
print yes


Let's say I've read the function, and I've seen this call site:

xyzzy([spam, eggs])


Now I want to change xyzzy:

def xyzzy(x):
if x:
print probably
if len(x) == 1:
print definitely


But there may be many call sites.  Perhaps xyzzy even implements part of
a poorly-documented external API.  So can x be None?  There's no way to
know short of checking all call sites, which may be impossible.  It may
not even be feasible to check the *only* call site, if you're
implementing somebody else's poorly documented closed-source API (a
situation I came across at work only yesterday, when that situation
resulted in a bug report).  If it's written this way, it's clear that it
can't be None:

def xyzzy(x):
if len(x) != 0:
print yes


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


Re: checking if a list is empty

2011-05-21 Thread Emile van Sebille

On 5/21/2011 7:46 AM John J Lee said...

Gregory Ewinggreg.ew...@canterbury.ac.nz  writes:


Hans Georg Schaathun wrote:

  0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.


0 does have some special properties, though, such as
being the additive identity and not having a multiplicative
inverse. Adding falseness as another special property isn't
too much of a stretch and turns out to be useful.

Likewise, it's useful to treat empty containers as having
a similar special property, since they're often a base or
terminating case in algorithms.

It's especially useful in a dynamic language where any
additional operations such as finding the length or
comparing with zero has a run-time cost.

Yes, you have to learn it, but it's a small thing to
learn with a considerable payoff.


(apologies if somebody already bikeshedded this argument in this thread)

In the absence of an explicit interface declaration (have any standards
emerged for that in Python 3, BTW?), the use of len() does give you some
information about the interface, which sometimes makes it easier to
change the function.

I'm sure you fully understand this, but I'll spell it out.  Consider
this function:

def xyzzy(x):
 if x:
 print yes


Let's say I've read the function, and I've seen this call site:

xyzzy([spam, eggs])


Now I want to change xyzzy:

def xyzzy(x):
 if x:
 print probably
 if len(x) == 1:
 print definitely


But there may be many call sites.  Perhaps xyzzy even implements part of
a poorly-documented external API.  So can x be None?  There's no way to
know short of checking all call sites, which may be impossible.  It may
not even be feasible to check the *only* call site, if you're
implementing somebody else's poorly documented closed-source API (a
situation I came across at work only yesterday, when that situation
resulted in a bug report).  If it's written this way, it's clear that it
can't be None:


qualified: ...without having been trapped or crashing so if I found 
this function in running code it would be clear to me that, given that 
the app is running and hasn't been crashing, either it hasn't yet been 
None, or the code isn't accessed at all.


Emile





def xyzzy(x):
 if len(x) != 0:
 print yes


John



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


Re: checking if a list is empty

2011-05-21 Thread Terry Reedy

On 5/21/2011 10:46 AM, John J Lee wrote:


In the absence of an explicit interface declaration (have any standards
emerged for that in Python 3, BTW?), the use of len() does give you some
information about the interface, which sometimes makes it easier to
change the function.

I'm sure you fully understand this, but I'll spell it out.  Consider
this function:

def xyzzy(x):
 if x:
 print yes


To me, this trivial procedure (it is not a mathematical function) is too 
unrealistic to be a basis for argument.



Let's say I've read the function, and I've seen this call site:

xyzzy([spam, eggs])

Now I want to change xyzzy:

def xyzzy(x):
 if x:
 print probably
 if len(x) == 1:
 print definitely


You are not changing xyzzy, you are replacing a procedure whose domain 
is all python objects with a new procedure with a much reduced domain. 
In other words, you are changing (and contracting) the idea of the 
procedure. This is a somewhat crazy thing to do and if Python developers 
did something like that in the stdlib, I would expect multiple protest 
posting ;-). (Adding code to *expand* the domain is a different matter.)


If xyzzy were really about sized collections, then
1. That should be documented *before* it is ever used in permanent code.
2. There should be code in the first production version that uses that 
fact and which would raise an error on other inputs.



But there may be many call sites.  Perhaps xyzzy even implements part of
a poorly-documented external API.  So can x be None?  There's no way to
know short of checking all call sites, which may be impossible.  It may
not even be feasible to check the *only* call site, if you're
implementing somebody else's poorly documented closed-source API (a
situation I came across at work only yesterday, when that situation
resulted in a bug report).  If it's written this way, it's clear that it
can't be None:

def xyzzy(x):
 if len(x) != 0:
 print yes


I agree that the domain of a function should be defined from the start 
(and only expanded in the future). This means considering from the 
start, or certainly once it runs correctly for intended inputs, what 
will happen for other inputs. For instance, I believe functions defined 
on counts (0, 1, 2, ...) should be written to avoid infinite looping on 
other inputs, in particular, fractional and negative numbers.  I can 
imagine in theory that a gratuitous call to len() might be useful for 
defining an interface, but as explained above, I am dubious about that 
in practice and do not find thid example convincing.



--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-21 Thread Steven D'Aprano
On Sat, 21 May 2011 15:46:01 +0100, John J Lee wrote:

 In the absence of an explicit interface declaration (have any standards
 emerged for that in Python 3, BTW?), the use of len() does give you some
 information about the interface, which sometimes makes it easier to
 change the function.

Er, yes? But in any realistic example (your trivial function xyzzyx below 
is not very realistic) you'll almost certainly get additional hints in 
the function body. If you have your stereotypical badly-documented 
function that does this:

def spam(x):
if x:
print(no)
# ...
x.append(42)
# ...

that's a hint that x is actually meant to be a list. If instead it says

x += 42

that's a good hint that x should not be a list. In either case, changing 
the test from if x to if x == [] or if len(x) == 0 or if x == 0 
doesn't gain you anything except a slightly longer average line length. 
If you're being paid by the character, that's an advantage, but 
otherwise, why bother?

True, if the function is sufficiently trivial, as in your xyzzyx example, 
then there won't be any such hints as to what sort of input the function 
expects. If that's the case, then chances are that the function accepts 
*any* object:

 def xyzzy(x):
 if x:
 print yes

and changing its semantics to only accept (say) lists, as in your 
example, is a risky thing to do.

It is *much* safer to leave that function untouched, create a new one:

def my_xyzzy(alist):
if alist:
print probably
if len(alist) == 1:
print definitely 

and then change the calls to xyzzyx into my_xyzzyx when and as you 
determine that it is safe to do so. That will ensure that if you miss a 
call of xyzzyx(42) somewhere deep in the library, the code will continue 
to run. If not, you'll have a dead function. You can always take it out 
later, once you are confident that it is indeed dead code.


[...]
 If it's written this way, it's clear that it can't be None:
 
 def xyzzy(x):
 if len(x) != 0:
 print yes


But you're assuming that the function actually is intended to accept only 
objects with a __len__ method. If that is the author's intention, there 
are better ways of signaling that fact.

I'm not entirely sure what your point is... is it to encourage lazy 
programmers to write len(x)==0 instead of documentation and meaningful 
names, or are you just pointing out the occasional silver-lining to a 
practice which is generally and usually unnecessary?



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


Re: checking if a list is empty

2011-05-21 Thread Chris Angelico
On Sun, May 22, 2011 at 11:02 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Sat, 21 May 2011 15:46:01 +0100, John J Lee wrote:

 Er, yes? But in any realistic example (your trivial function xyzzyx below
 is not very realistic) you'll almost certainly get additional hints in
 the function body.

True, but sometimes those hints will be buried in nested calls, making
it less obvious. It might well take some digging to figure out just
what sort of object it's meant to be accepting. That's why I prefer to
have some sort of type declarations; or alternatively, a good
docstring / autodoc comment that says what the function wants and
gives.

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


Re: checking if a list is empty

2011-05-21 Thread rusi
On May 22, 1:11 am, Terry Reedy tjre...@udel.edu wrote:

 I agree that the domain of a function should be defined from the start
 (and only expanded in the future).

I dont understand...
I dont always write correct code -- otherwise called 'a bug' -- though
I never let the damn bug lose intentionally.
And when I see 'the bug' scampering around to my distress the only way
of catching it sometimes is to strengthen an (perhaps earlier
unthought, unspecified) invariant or precondition.
Which amounts to contracting the domain.

 This is a somewhat crazy thing to do and if Python developers
 did something like that in the stdlib, I would expect multiple protest
 posting ;-).

That such protests happen is evidence (I dont say proof) that such
contractions are sometimes necessary.   In fact when I pick up some
code marked as 'alpha' I understand it as saying:
Please try this and send us (the developers) bug reports. But in no
case are we committed to the current API.
[Sometimes this is explicitly said. It is always implied by the
'alpha']

When I see 'Beta' I understand: We think this works and we will not
make gratuitous changes but no guarantees.

When I see 'Stable' I understand: The API is fixed (ie we will not
change it) and we accept the inevitable consequence [Seventh Lehman-
Belady law:
http://en.wikipedia.org/wiki/Lehman%27s_laws_of_software_evolution ]

Why is the C library in linux called libc6 and not just libc?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-21 Thread Chris Angelico
On Sun, May 22, 2011 at 1:02 PM, rusi rustompm...@gmail.com wrote:
 Why is the C library in linux called libc6 and not just libc?

I assume you mean this? http://www.linux-m68k.org/faq/glibcinfo.html

When you dynamically link against a shared object, you save on
executable size, but you have to have that shared object on the target
system. That's completely different from API changes. I could compile
my code using half a dozen different compilers, and use dynamic
linking each time, and then those six binaries would expect six
implementations of libc on the target computer. They're incompatible
with each other. But they will all have a size_t strlen(const char *)
that tells me how long my string is.

Everyone has a different way of handling incompatible API changes. The
most common is to simply deprecate the old function and create a new
one. It's simple and effective. With your original xyzzy function,
create a my_xyzzy as per Steven's suggestion; job done. (I'd assume
that a function called my_xyzzy is a local override, in the same way
that I might write a my_malloc that does some statisticking and then
returns malloc(sz), but that's one of the consequences of trivia - you
can't really name it descriptively.)

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


Re: checking if a list is empty

2011-05-21 Thread rusi
On May 22, 8:52 am, Chris Angelico ros...@gmail.com wrote:
 On Sun, May 22, 2011 at 1:02 PM, rusi rustompm...@gmail.com wrote:
  Why is the C library in linux called libc6 and not just libc?

 I assume you mean this?http://www.linux-m68k.org/faq/glibcinfo.html

Ha Ha! Thanks for that link! I quote:

 You should not be using libc4 for anything any more. If you do use it, we 
 will hunt you
 down and execute you as an example to others. (Not really, but you get the 
 point...)

Recently on the emacs list there was a big flame-fest because the
behavior (aka interface) of return/newline changed.
The argument for change: Can we have emacs behave a little more like a
21st century application?
Against: Somebody's scripting code broke badly.

You may take any side you like.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-21 Thread Chris Angelico
On Sun, May 22, 2011 at 2:32 PM, rusi rustompm...@gmail.com wrote:
 Recently on the emacs list there was a big flame-fest because the
 behavior (aka interface) of return/newline changed.
 The argument for change: Can we have emacs behave a little more like a
 21st century application?
 Against: Somebody's scripting code broke badly.

 You may take any side you like.

The side I take is: If you want emacs, use emacs. If you want SciTE,
use SciTE. If you want nano, use nano. And sometimes, you might have
special circumstances that demand a different choice (can't use SciTE
over ssh, afaik), so it's worth learning more than one.

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


Re: checking if a list is empty

2011-05-16 Thread rusi
On May 16, 2:36 am, Terry Reedy tjre...@udel.edu wrote:
 On 5/15/2011 1:33 PM, rusi wrote:

  On May 15, 10:07 am, Steven D'Apranosteve
  +comp.lang.pyt...@pearwood.info  wrote:

  I'm afraid I don't understand what you mean. Can you explain please, what
  properties of first class booleans do you think are missing from Python?

 Given the usual CS definition of 'first class object', all Python
 objects are first class. But that does not preclude other definitions.

 snipped

 What CS definition?

Perhaps your definition matches the wikipedia article:
http://en.wikipedia.org/wiki/First-class_object

And I am using the extended definition on the talk page:
http://en.wikipedia.org/wiki/Talk:First-class_object#Is_it_is.2C_or_is_it_aint.3F

[Evidently the arguments of this thread are repeatedly played out
elsewhere :-; ]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread rusi
On May 15, 10:07 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 I'm afraid I don't understand what you mean. Can you explain please, what
 properties of first class booleans do you think are missing from Python?


Dijkstra's writings I alluded to, take a logic/math line to this.  Let
me try to rephrase Dijkstra (who is now sadly not able to defend our
(mis)understandings of his writings) in a more linguistic way:

In English when we say something like x is y  the y (predicate) can
be an adjective phrase -- the apple is red -- or a noun phrase -- the
apple is a fruit.

They seem similar; they are very different -- you agree??

From times immemorial 'true' and 'false' have been used in the
adjective sense: eg Such-and-such statement is true.
Boole's contribution -- actually Dijkstra's recognition of Boole's
contribution -- is that dignifying {true, false} from adjectives to
nouns -- the boolean domain -- fundamentally alter and improve the
rules and possibilities for our thinking. [See his puzzles in the same
paper:
http://www.google.com/url?sa=Dq=http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

As an analogy for this consider arithmetic.

Even primitive people can count: My 3 children, my 5 sheep.  They do
this with the ordinals -- first child, second child, third child...
But arithmetic cannot really take off until we allow these numbers
(ordinals) to be dignified into entities in their own right --
cardinals.
ie the mathematician needs to believe in the existence of the numbers
1,2 etc for him to do his job well.

[As an aside I may mention that philosophers of mathematicians will
call this platonism: In which heaven do these numbers exist?
And platonism is mysticism. And mysticism is bullshit.  But the vast
majority of practicing mathematicians refuse to be dislodged from
their 'platonic heaven.'  For them mathematics can only be done if it
is done in 'discovery' mode and not in 'invention' mode.]

And so just as good math happens by believing that the numbers exist
and discovering their properties, good logic happens when we believe
that {True, False} exist (in some platonic heaven). Which is to say
they should be nouns in our language.

Well that in summary is the Boole's ideology (Dijkstra's evangelism)
understood linguistically and independent of python/programming.

Reapplied back to the math/programming field, we find that if a value-
domain (data-type) has to be first-class, it at the least has to be a
denotable entity in the language which should be conformable with its
abstract/expected properties.
For example if my language seems to have entities like '2' '3' '+' but
2+3 does not work out equal to 5 we would (I hope!) not say the
language has first-class numbers.

But in order for any of this discussion to be possible, equality
should be well-defined.
Which means that in addition to being an equivalence relation it must
have substitutivity
http://en.wikipedia.org/wiki/Equality_%28mathematics%29#Some_basic_logical_properties_of_equality
which is another form of a very fundamental principle attributed to
Leibniz, the principle of identity of indiscernibles:
http://en.wikipedia.org/wiki/Leibniz%27s_law

Seemingly you and Dijkstra are saying something similar when you say
[1,2,3] is a way of writing true
and he says 23 is a way of writing true.
But on further examination (with Leibniz law above) Dijkstra's 23 =
True will work consistently in all contexts but [1,2,3] = True will
work sometimes and fail sometimes.

In mathSpeak we say, the definition of bool is not well defined
In CSSpeak we say the definition is not first class.

In the language of algebraic specifications, the slogan is No
confusion, No junk
eg 
http://www.informatik.uni-bremen.de/agbkb/lehre/ws06-07/casl/slides/Datatypes-II.pdf

This is usually applied to specific models in a given language

But it could as well be applied to the models that a language supplies
by default.
And when we apply it to python's bool as a model of the abstract/math
concept bool it has confusion and junk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread Terry Reedy

On 5/15/2011 1:33 PM, rusi wrote:

On May 15, 10:07 am, Steven D'Apranosteve
+comp.lang.pyt...@pearwood.info  wrote:


I'm afraid I don't understand what you mean. Can you explain please, what
properties of first class booleans do you think are missing from Python?


Given the usual CS definition of 'first class object', all Python 
objects are first class. But that does not preclude other definitions.



Dijkstra's writings I alluded to, take a logic/math line to this.  Let
me try to rephrase Dijkstra (who is now sadly not able to defend our
(mis)understandings of his writings) in a more linguistic way:

In English when we say something like x is y  the y (predicate) can
be an adjective phrase -- the apple is red -- or a noun phrase -- the
apple is a fruit.

They seem similar; they are very different -- you agree??


Sometimes. Sometimes it could mean 'the apple is fruity' or 'the apple 
has the characters that define the wider grouping of fruits'. John is 
brilliant, John is a brilliant man, and John is a genius (there is 
no 'a brilliant') pretty much have the same effective meaning. But I get 
the point about reification.



From times immemorial 'true' and 'false' have been used in the

adjective sense: eg Such-and-such statement is true.
Boole's contribution -- actually Dijkstra's recognition of Boole's
contribution -- is that dignifying {true, false} from adjectives to
nouns -- the boolean domain -- fundamentally alter and improve the
rules and possibilities for our thinking. [See his puzzles in the same
paper:
http://www.google.com/url?sa=Dq=http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

As an analogy for this consider arithmetic.

Even primitive people can count: My 3 children, my 5 sheep.  They do
this with the ordinals -- first child, second child, third child...
But arithmetic cannot really take off until we allow these numbers
(ordinals) to be dignified into entities in their own right --
cardinals.
ie the mathematician needs to believe in the existence of the numbers
1,2 etc for him to do his job well.

[As an aside I may mention that philosophers of mathematicians will
call this platonism: In which heaven do these numbers exist?
And platonism is mysticism. And mysticism is bullshit.  But the vast
majority of practicing mathematicians refuse to be dislodged from
their 'platonic heaven.'  For them mathematics can only be done if it
is done in 'discovery' mode and not in 'invention' mode.]

And so just as good math happens by believing that the numbers exist
and discovering their properties, good logic happens when we believe
that {True, False} exist (in some platonic heaven). Which is to say
they should be nouns in our language.

Well that in summary is the Boole's ideology (Dijkstra's evangelism)
understood linguistically and independent of python/programming.

Reapplied back to the math/programming field, we find that if a value-
domain (data-type) has to be first-class, it at the least has to be a
denotable entity in the language which should be conformable with its
abstract/expected properties.
For example if my language seems to have entities like '2' '3' '+' but
2+3 does not work out equal to 5 we would (I hope!) not say the
language has first-class numbers.


You seem to equate 'number' with 'natural number' in the classical 
sense. If '2' and '3' are residue classes (remainers) mod 5, then 2 + 3 
is 0. Even kids understand clock arithmetics. Of course,

the 24 hour (0 to 23 hourse) is saner than the older 1-12,am/pm system,
but kids even manage with that.


But in order for any of this discussion to be possible, equality
should be well-defined.
Which means that in addition to being an equivalence relation it must
have substitutivity
http://en.wikipedia.org/wiki/Equality_%28mathematics%29#Some_basic_logical_properties_of_equality
which is another form of a very fundamental principle attributed to
Leibniz, the principle of identity of indiscernibles:
http://en.wikipedia.org/wiki/Leibniz%27s_law

Seemingly you and Dijkstra are saying something similar when you say
[1,2,3] is a way of writing true
and he says 23 is a way of writing true.
But on further examination (with Leibniz law above) Dijkstra's 23 =
True will work consistently in all contexts


In general, a  b will work consistently as generally expected of total 
orders if, but only if, a and b are members of a totally ordered set and 
 indicates that total order. If '' represents a partial order, 'ab' 
may be undefined or defined as false when 'ba' is also false.


 but [1,2,3] = True will work sometimes and fail sometimes.

'Bool(normal expression*) is a much a spelling of true or false as 'a 
 b'. It works just as consistently in all contexts.


*nornal expression: evaluates to an object with a well-defined boolean 
value, which is to say, causes bool() to return True or False.



In mathSpeak we say, the definition of bool is not well defined


The math definition of bool or the Python definition?
And 

Re: checking if a list is empty

2011-05-15 Thread Steven D'Aprano
On Sun, 15 May 2011 10:33:38 -0700, rusi wrote:

 On May 15, 10:07 am, Steven D'Aprano steve
 +comp.lang.pyt...@pearwood.info wrote:

 I'm afraid I don't understand what you mean. Can you explain please,
 what properties of first class booleans do you think are missing from
 Python?

[snip]

I'm afraid I didn't find your discussion about reification, Platonism and 
linguistics very helpful. Some of it I disagree with, some I agree with, 
but in neither case do I see any relevance to the question of whether 
bools are first class objects in Python, and if not, why not.


 Reapplied back to the math/programming field, we find that if a value-
 domain (data-type) has to be first-class, it at the least has to be a
 denotable entity in the language which should be conformable with its
 abstract/expected properties.

Now you're getting somewhere!

 For example if my language seems to have entities like '2' '3' '+' but
 2+3 does not work out equal to 5 we would (I hope!) not say the language
 has first-class numbers.

Well, that's a problem. By that definition, floats are not first class 
numbers. While 2+3 does work out to be equal to 5, other standard 
properties of the real number system do not apply:

 0.3 + 0.4 - 0.3 == 0.4
False

Similarly, in many languages (including older versions of Python), 
neither are integers:

 2147483647 + 1
Traceback (innermost last):
  File stdin, line 1, in ?
OverflowError: integer addition


Other languages may wrap around, giving -1 or -2147483648.

So it seems that either we're forced to accept that neither floats nor 
integers are first class, or instead back-track and ask:

Hang on, who decides what the expected properties are?



 But in order for any of this discussion to be possible, equality should
 be well-defined.
 Which means that in addition to being an equivalence relation it must
 have substitutivity


Can you show us a problem that is hard to solve in Python because ([1,2] 
and True) evaluates as True, but ([1,2] == True) evaluates as False?



 http://en.wikipedia.org/wiki/Equality_%28mathematics%
29#Some_basic_logical_properties_of_equality
 which is another form of a very fundamental principle attributed to
 Leibniz, the principle of identity of indiscernibles:
 http://en.wikipedia.org/wiki/Leibniz%27s_law

But Python truth values are not indiscernible. Do you think they must be?

If they are indiscernible, there can only be two unique values (possibly 
spelled Veritas and Falsus to avoid confusion with Python's True and 
False). But why must they be indiscernible?


 Seemingly you and Dijkstra are saying something similar when you say
 [1,2,3] is a way of writing true
 and he says 23 is a way of writing true. But on further examination
 (with Leibniz law above) Dijkstra's 23 = True will work consistently in
 all contexts but [1,2,3] = True will work sometimes and fail sometimes.

Please do not arbitrarily mix Python and mathematics syntax. What you 
have stated gives a SyntaxError.

[1,2,3] == True will work always, or you have a very buggy version of 
Python. It will always return False, as expected.


I suspect that in a boolean context, the operator you want is material 
biconditional, or XNOR, also known as p if and only if q. Python does 
not have this as a built-in, but it's easy enough to write it:

def xnor(p, q):
if p: return q
else: return p if q else True

(I have deliberately written it to return one of the two arguments when 
possible. If you don't care for this behaviour, the else clause is even 
simpler: return not q)

If you don't like the name XNOR, rename it equals and be done. Nobody 
says that equality *must* be spelled with = or == as an infix operator. 
That would be a foolish insistence.

Another way would be to compare the canonical truth values for equality:

bool(p) == bool(q)

but of course there's nothing special about the canonical truth values 
except ease of use. One could choose any other values:

def canonical(flag):
if flag: return Nobody expects the Spanish Inquisition!!!
else: return None

canonical(p) == canonical(q)

The important thing is that Python's sense of equality doesn't just apply 
in the boolean domain, it applies to the broader any-arbitrary-Python-
object domain. Python's equals is too powerful to be limited to Python's 
truth values: it needs to distinguish between 42 and 23, while in the 
boolean domain one need not.

Consequently, if you want equality in the boolean domain, you need to use 
something other than the built-in == operator. Python doesn't allow you 
to override == for built-in objects, so the simplest, most straight-
forward way is with a function. Using such a function:

 equals = xnor
 equals( equals([1, 2], 42), equals(spam, 23) )
23

which is, naturally, just another way of spelling True.



 In mathSpeak we say, the definition of bool is not well defined In
 CSSpeak we say the definition is not first class.

That is not the normal definition of first class in computer 

Re: checking if a list is empty

2011-05-15 Thread harrismh777

rusi wrote:

But on further examination (with Leibniz law above) Dijkstra's 23 =
True will work consistently in all contexts but [1,2,3] = True will
work sometimes and fail sometimes.


It would have to be written 23 == True;  [1,2,3] == True;  otherwise,

...

+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread Terry Reedy

On 5/15/2011 5:36 PM, Terry Reedy wrote:

On 5/15/2011 1:33 PM, rusi wrote:



Dijkstra's writings I alluded to,


at
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

Acquiring that familiarity requires what in these financial times is 
known as intellectual investment; you can take my word for it that 
this investment quickly pays off.


I recommend understanding the following as three more intellectual 
investments:


We create a Boolean domain by drawing a distinction in some domain and 
treating everything on each side of the distinction as equal in some 
value. A Boolean value or variable represents such a dichotomy, a choice 
between two all-inclusive but mutually exclusive possibilities. Boole 
derived his domain from truth/falsity of propositions. But that is an 
interpretation of his abstract model and only one of endless possibilities.


This realization that switching networks are another interpretation is 
the basis of digital computation. Boolean algebra theorems are theorems 
about switching networks and can be used to design such networks. Such 
networks can be used to do boolean arithmetic. The trick is to coerce 
physical components into one of two states. Part of the trick is to not 
look when they are transiting between them.


For its built-in information objects, Python choose 'representation of 
something' versus 'representation of nothing' as the dichotomy. It 
matches 'something' to True and 'nothing' to False as this is generally 
more useful than the opposite matching. In boolean contexts, it 
automatically fetches the boolean value of an object.


--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-15 Thread harrismh777

Steven D'Aprano wrote:

I'm afraid I don't understand what you mean. Can you explain please,





http://www.informatik.uni-bremen.de/agbkb/lehre/ws06-07/casl/slides/Datatypes-II.pdf


Geeze,  I wonder if software is mathematics



kind regards,
m harris



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


Re: checking if a list is empty

2011-05-15 Thread Algis Kabaila
On Friday 13 May 2011 18:47:50 Hans Georg Schaathun wrote:
 On Thu, 12 May 2011 23:20:20 +1000, Chris Angelico
 
   ros...@gmail.com wrote:
 :  Writing a program requires expertise both in programming
snip...
 
 And the main difference here, is that the civil engineers
 have a much better language to share information.  The best
 programmers have is the programming language, and we ought
 to make that as good as possible.

As an old Civil Engineer and a retired educator of Civil and 
Aeronautical Engineers, I want to get at the end of the long 
thread.  Early in the thread I (wrongly) thought that the 
discussion just did not make sense.  Much as has been said, 
makes a good sense, though some of it is hardly relevant.  So 
what is the purpose of this discussion - is it to proffer advice 
to the Benevolent Dictator for life and to his cohort or is it 
to better understand the programming language Python?

In relation to the first part of the question is that the aim is 
far too ambitious - the success of Python language is enough to 
suggest that Guido and his team do not need advice and they will 
ask for it if they really do want to hear the opinions about it.  
The job they have done in developing the language is admirable 
and the users better concentrate on trying to understand it 
better.

The second part of the (rhetorical) question is that the answer 
depends what the designers of Python have chosen as criterion 
for True or False. In my little effort to present Vector 
algebra in an easy to use manner
(refer to thread of yesterday: Python 3.2 Vectors.py module)
it was necessary to answer the question of what could and what 
should be used to determine what the instruction '=='  or  '='  
should mean and what should be used for comparison.  The only 
one that I could find useful was the equality - two vectors are 
equal if and only if all three of their components are equal.  
As the components (for purposes of engineering analysis) are 
real numbers, even the postulation of (v1.x == v2.x) is 
problematic, as has been pointed out in the thread (as the 
floats are subject to unavoidable round off errors).  So the 
answers are not necessarily unique and one must consider what 
the program is supposed to achieve.

BTW, the Vector class inherits from the list, which  avoids 
reinventing the wheel. The other operators are assigned 
specific purposes, viz. v1 * v2 is a scalar product of two 
vectors (the result is a scalar, float), while v1 * r  (where v1 
is a vector and r is a float) is scaling the size of vector by 
factor r,  (the result is a vector) i.e. each component of v1 is 
multiplied by r.

Vector product (cross product) is shown as  v1 ** v2 (the result 
is a vector).  The purpose of choosing this scheme is neither 
linguistic, nor philosophical - it is practical, just as the 
vector algebra is practical.  It helps to visualise solutions of 
physical problems (or, if you prefer, engineering problems).

OldAl.
-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread rusi
I have been scolded off-list for pursuing a discussion that has
nothing to do with python.
So I continue a bit gingerly :-)  and will stop when others feel this
is useless/irrelevant/whatever.

Steven wrote:

 I'm afraid I didn't find your discussion about reification, Platonism and
 linguistics very helpful. Some of it I disagree with, some I agree with,
 but in neither case do I see any relevance to the question of whether
 bools are first class objects in Python, and if not, why not.

Thank you (Steven and Terry) for using the word 'reification'. I used
the more common 'firstclass' because I assumed that will be more
generally known. I however prefer reification since one can discuss
(more cooly :-) ) what and how much one should reify; the word
reification has less of a strong value judgment in philosophy than
firstclass has in computer science.

The lead-writeup on reification 
http://en.wikipedia.org/wiki/Reification_%28computer_science%29
has the following line:
 Informally, reification is often referred to as making something a 
 first-class citizen within the scope of a particular system.

So from the CS side reification == movement-towards-firstclassness
From the philosophical side we could try to define platonism (non-
mystically) as The strong reification of abstract concepts

So much for my defense of bringing in platonism into the discussion.

Steven wrote:

  Seemingly you and Dijkstra are saying something similar when you say
  [1,2,3] is a way of writing true
  and he says 23 is a way of writing true. But on further examination
  (with Leibniz law above) Dijkstra's 23 = True will work consistently in
  all contexts but [1,2,3] = True will work sometimes and fail sometimes.

 Please do not arbitrarily mix Python and mathematics syntax. What you have 
 stated gives a SyntaxError.

Is this non-mixing-up possible? Like 'reification,' I do not know if
using the funny brackets of denotational semantics would be
intelligible on this list ( and I dont know how to write them in
ASCII) but using |[ ]| as an approximation, I would have to say
something like:

Dijkstra's |[ 23 ]| = True will work consistently... Python's |
[ [1,2,3] ]|  = |[True ]| will be be true in boolean contexts and not
elsewhere.
Note that the first |[]| is for the object language called mathematics
and the other two for the object language called python. And the = is
in a pidgin English-math meta language that is need to discuss these
object languages.

I am not clear that this form of discourse actually enhances clarity,
however it does bring up the point that this discussion is as much
about object/meta-language distinctions and confusions as it is about
reification.

You see when Terry talks of boolean algebra for switching networks, he
is referring to logic as an object language.
But when we use logic to discuss and understand (and argue :-) ) we
are using  it in the meta-language.

Dijkstra's signal contribution -- which he attributes to Boole,
Leibniz and Recorde (for the = sign) -- lies in this:
From the time of Aristotle, all usage of logic in the meta-language
(logic as the substrate for arguments rather than logic as a model for
things like switching networks)  has been a string of assertions
linked up with 'implies' 'therefore' 'follows from' etc.  All these
when modelled (in a suitable object logic) would traditionally look
like = (implies) or at best = (follows from)

It is possible to do all this -- traditional logic -- using = (aka
iff, =, etc)

The benefit is that logic becomes much more like traditional algebra:
Proofs become of the form:

desideradum
=
:
:
= true

The cost is that bool has to be properly reified.

Steven wrote:
 Rusi wrote:
  For example if my language seems to have entities like '2' '3' '+' but
  2+3 does not work out equal to 5 we would (I hope!) not say the language
  has first-class numbers.

 Well, that's a problem. By that definition, floats are not first class
 numbers. While 2+3 does work out to be equal to 5, other standard
 properties of the real number system do not apply:

  0.3 + 0.4 - 0.3 == 0.4

From C onwards (and in Fortran), its been called float, not real.
Note that C like python uses a math-suggesting name int for integers
but a hardware implementation name for float.  This suggests that
(aside from overflow) int in C corresponds to the math Z whereas float
does not quite correspond to real.  [The whole field of numerical
analysis comes about because of this non-correspondence]

In the language Pascal, what we call float today was called real and
this would be an argument.
But in this context I dont get the argument...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Ian Kelly
On Fri, May 13, 2011 at 10:47 PM, harrismh777 harrismh...@charter.net wrote:
 http://www.inf.ed.ac.uk/teaching/courses/inf1/fp/

 http://www.cs.ou.edu/~rlpage/fpclassSpring97/


 There are lots of these...   the two above afaik are still doing this at the
 entry level...    ... supposedly, these kids are 'mostly' successful and
 exit interviews are great...  but that doesn't fit with the observed idea
 that students are not doing well in comp sci classes generally... but, read
 below...  this at the entry level??

I'll grant you Edinburgh.  That Oklahoma syllabus is from 1997.  The
2010 syllabus for the entry-level course indicates that it is taught
in Java.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Steven D'Aprano
On Thu, 12 May 2011 23:46:12 -0700, rusi wrote:

 Mathematics has existed for millenia. Hindu-arabic numerals (base-10
 numbers) have been known for about one millennium
 The boolean domain is only a 100 years old. Unsurprisingly it is not
 quite 'first-class' yet: See
 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
 [Lifted from http://c2.com/cgi/wiki?EqualVsTrueFalse ]

Th money-quote as regards using arbitrary objects in truth tests:

[quote]
All this changed with the introduction of the two-element 
boolean domain {true, false} which provides the vocabulary 
needed to assign values to boolean expressions: 34 is a 
way for writing true, 34 is a way for writing false, 
whereas the value of x0 depends on the value of x ...
[end quote]


In Python, [1, 2, 3] is another way of writing true, and [] is another 
way of writing false. Similarly with any other arbitrary objects. The 
only things that bools True and False are good for are:

* giving functions a canonical way of spelling true/false when they want 
to emit a Boolean value;

* giving documentation writers a canonical way of spelling true/false 
when they want to discuss passing a Boolean value.

Other than those conveniences, there's nothing you can do with True and 
False in Python that you can't do with any other set of objects.


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


Re: checking if a list is empty

2011-05-14 Thread rusi
On May 14, 12:39 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 On Thu, 12 May 2011 23:46:12 -0700, rusi wrote:
  Mathematics has existed for millenia. Hindu-arabic numerals (base-10
  numbers) have been known for about one millennium
  The boolean domain is only a 100 years old. Unsurprisingly it is not
  quite 'first-class' yet: See
 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
  [Lifted fromhttp://c2.com/cgi/wiki?EqualVsTrueFalse]

 Th money-quote as regards using arbitrary objects in truth tests:

     [quote]
     All this changed with the introduction of the two-element
     boolean domain {true, false} which provides the vocabulary
     needed to assign values to boolean expressions: 34 is a
     way for writing true, 34 is a way for writing false,
     whereas the value of x0 depends on the value of x ...
     [end quote]

 In Python, [1, 2, 3] is another way of writing true, and [] is another
 way of writing false. Similarly with any other arbitrary objects.

Well so is [1,2] another way of writing True

And then we get the interesting result that
(True = True) is False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Hans Mulder

On 07/05/2011 02:43, Jon Clements wrote:

On May 7, 12:51 am, Ian Kellyian.g.ke...@gmail.com  wrote:

On Fri, May 6, 2011 at 4:21 PM, Philip Semanchukphi...@semanchuk.com  wrote:

What if it's not a list but a tuple or a numpy array? Often I just want to 
iterate through an element's items and I don't care if it's a list, set, etc. 
For instance, given this function definition --



def print_items(an_iterable):
if not an_iterable:
print The iterable is empty
else:
for item in an_iterable:
print item



I get the output I want with all of these calls:
print_items( list() )
print_items( tuple() )
print_items( set() )
print_items( numpy.array([]) )


But sadly it fails on iterators:
print_items(xrange(0))
print_items(-x for x in [])
print_items({}.iteritems())


My stab:

from itertools import chain

def print_it(iterable):
 it = iter(iterable)
 try:
 head = next(it)
 except StopIteration:
 print 'Empty'
 return
 for el in chain( (head,), it ):
 print el

Not sure if I'm truly happy with that though.


How about:

def print_items(an_iterable):
found_item = False
for item in an_iterable:
print item
found_item = True
if not found_item:
print The iterable was empty

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


Re: checking if a list is empty

2011-05-14 Thread Chris Angelico
On Sat, May 14, 2011 at 5:45 PM, rusi rustompm...@gmail.com wrote:
 And then we get the interesting result that
 (True = True) is False

How does this work? In Python, the = sign is illegal there, and if you
mean True == True, then it's True (obviously), which is not False.

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


Re: checking if a list is empty

2011-05-14 Thread David Robinow
On Fri, May 13, 2011 at 10:34 PM, Gregory Ewing
greg.ew...@canterbury.ac.nz wrote:
 rusi wrote:

 Dijkstra's problem (paraphrased) is that python, by choosing the
 FORTRAN alternative of having a non-first-class boolean type, hinders
 scientific/mathematical thinking/progress.

 Python doesn't have the flaw that Dijkstra was talking about.
 Fortran's flaw wasn't so much the lack of a boolean type, but
 that you couldn't assign the result of a logical expression to
 a variable. Python has always been able to do that, even before
 it had a distinct boolean type.
And Fortran could do it at least 25 years before Python was invented.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Roy Smith
In article mailman.1549.1305383294.9059.python-l...@python.org,
 David Robinow drobi...@gmail.com wrote:

 On Fri, May 13, 2011 at 10:34 PM, Gregory Ewing
 greg.ew...@canterbury.ac.nz wrote:
  rusi wrote:
 
  Dijkstra's problem (paraphrased) is that python, by choosing the
  FORTRAN alternative of having a non-first-class boolean type, hinders
  scientific/mathematical thinking/progress.
 
  Python doesn't have the flaw that Dijkstra was talking about.
  Fortran's flaw wasn't so much the lack of a boolean type, but
  that you couldn't assign the result of a logical expression to
  a variable. Python has always been able to do that, even before
  it had a distinct boolean type.
 And Fortran could do it at least 25 years before Python was invented.

I vaguely remember that Fortran called the data type LOGICAL, but yes, 
it was exactly what most modern languages call a bool or boolean.  And 
the operators were spelled .NOT., .AND., .OR., etc but that's because 
Fortran was designed for punch cards, which didn't have much in the way 
of special characters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread rusi
On May 14, 6:42 pm, Chris Angelico ros...@gmail.com wrote:
 On Sat, May 14, 2011 at 5:45 PM, rusi rustompm...@gmail.com wrote:
  And then we get the interesting result that
  (True = True) is False

 How does this work? In Python, the = sign is illegal there, and if you
 mean True == True, then it's True (obviously), which is not False.

 Chris Angelico

1. = vs ==
Ok to be true to python syntax I should have said (True == True) is
False.
But then the question arises, is the is a python is or an English is?
If its python then that's fine but its just bland code with no
discussion about it.
To say something about it (in English) one would have to say
(True == True) is False is True (where the first is is a python is and
the second an English one).

2. True == True is (obviously) True

Here is the quote (with internal quote from Dijkstra) from Steven that
I was answering:

--
[Dijkstra quote]
All this changed with the introduction of the two-element
boolean domain {true, false} which provides the vocabulary
needed to assign values to boolean expressions: 34 is a
way for writing true, 34 is a way for writing false,
whereas the value of x0 depends on the value of x ...
[end quote]

[Steven quote]
In Python, [1, 2, 3] is another way of writing true, and [] is another
way of writing false. Similarly with any other arbitrary objects. The
only things that bools True and False are good for are:
snipped
[end Steven quote]


So since
[1,2,3] is one way of writing True (lets call it True3)
and [1,2] is another (call it True2)
then we have True3 == True2 is False

But since according to Steven (according to Python?) True3 *is the
same* as True2
we get
  False
= [1,2,3] == [1,2]
= True3  == True2
= True == True
= True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Chris Angelico
On Sun, May 15, 2011 at 1:47 AM, rusi rustompm...@gmail.com wrote:
 So since
 [1,2,3] is one way of writing True (lets call it True3)
 and [1,2] is another (call it True2)
 then we have True3 == True2 is False

 But since according to Steven (according to Python?) True3 *is the
 same* as True2
 we get
  False
 = [1,2,3] == [1,2]
 = True3  == True2
 = True == True
 = True

Okay, I see what you're doing here.

http://www.rinkworks.com/ithink/search.cgi?words=compress

When you condense a whole lot of information down to just two states,
True and False, *obviously* there'll be a huge amount that fits into
one or the other without being identical. It's not an argument for
whether [1,2,3] ought to be True or ought to be False. You could make
the exact same argument if they evaluated to False. You have proven
nothing and just wasted your time proving it.

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


Re: checking if a list is empty

2011-05-14 Thread rusi
On May 14, 8:55 pm, Chris Angelico ros...@gmail.com wrote:
 On Sun, May 15, 2011 at 1:47 AM, rusi rustompm...@gmail.com wrote:
  So since
  [1,2,3] is one way of writing True (lets call it True3)
  and [1,2] is another (call it True2)
  then we have True3 == True2 is False

  But since according to Steven (according to Python?) True3 *is the
  same* as True2
  we get
   False
  = [1,2,3] == [1,2]
  = True3  == True2
  = True == True
  = True

 Okay, I see what you're doing here.

 http://www.rinkworks.com/ithink/search.cgi?words=compress

LOL -- Thanks for that.

But it seems you did not get the moral? Spelt out: Beware of lossy
compression!
[Which is also the moral of my 'proof']


 When you condense a whole lot of information down to just two states,
 True and False, *obviously* there'll be a huge amount that fits into
 one or the other without being identical. It's not an argument for
 whether [1,2,3] ought to be True or ought to be False. You could make
 the exact same argument if they evaluated to False. You have proven
 nothing and just wasted your time proving it.

 Chris Angelico

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


Re: checking if a list is empty

2011-05-14 Thread Terry Reedy

On 5/14/2011 3:39 AM, Steven D'Aprano wrote:


Th money-quote as regards using arbitrary objects in truth tests:

 [quote]
 All this changed with the introduction of the two-element
 boolean domain {true, false} which provides the vocabulary
 needed to assign values to boolean expressions: 34 is a
 way for writing true, 34 is a way for writing false,
 whereas the value of x0 depends on the value of x ...
 [end quote]


In Python, [1, 2, 3] is another way of writing true, and [] is another
way of writing false. Similarly with any other arbitrary objects.


Another way to look at it is that Python automatically calls bool() on 
every expression in its two boolean or conditional contexts: 'if e:' and 
'while e'. This is a boilerplate-removing, labor-saving convenience. 
Python has many such conveniences.


--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-14 Thread Terry Reedy

On 5/14/2011 3:45 AM, rusi wrote:


(True = True) is False


is a syntax error ;-)

and 'True = True' is a (useless) statement,
and statements do not have boolean values,
and 'True == True' *is* True, which is to say,
((True == True) is False) is False.

--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-14 Thread Terry Reedy

On 5/14/2011 1:43 PM, rusi wrote:


But it seems you did not get the moral? Spelt out: Beware of lossy
compression!
[Which is also the moral of my 'proof']


I get it now. As I suggested in response to Stephen, [] and [1] spell 
False and True only in boolean contexts (if/while headers) where they 
are implicitly wrapped with a bool() call, which is to say, where their 
boolean value is extracted from them. As you point out, there is 
information loss as all other context-irrelevant details are ignored.


--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-14 Thread Ben Finney
rusi rustompm...@gmail.com writes:

 [Steven quote]
 In Python, [1, 2, 3] is another way of writing true, and [] is another
 way of writing false. Similarly with any other arbitrary objects. The
 only things that bools True and False are good for are:
 snipped
 [end Steven quote]
 

 So since
 [1,2,3] is one way of writing True (lets call it True3)

No. Steven knew exactly why he was using “true” versus “True”. He's
explained why elsewhere in this thread. The former does not refer to the
Python boolean singleton, the latter does.

The only object that is True is the True singleton. But there are many
objects that are true.

-- 
 \ “I got up the other day, and everything in my apartment has |
  `\   been stolen and replaced with an exact replica.” —Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread rusi
On May 15, 4:26 am, Ben Finney ben+pyt...@benfinney.id.au wrote:
 rusi rustompm...@gmail.com writes:
  [Steven quote]
  In Python, [1, 2, 3] is another way of writing true, and [] is another
  way of writing false. Similarly with any other arbitrary objects. The
  only things that bools True and False are good for are:
  snipped
  [end Steven quote]
  

  So since
  [1,2,3] is one way of writing True (lets call it True3)

 No. Steven knew exactly why he was using “true” versus “True”. He's
 explained why elsewhere in this thread. The former does not refer to the
 Python boolean singleton, the latter does.

 The only object that is True is the True singleton. But there are many
 objects that are true.

Yes.
The python entities: {True, False} are not an exact (isomorphic) model
for the semantic boolean domain {true, false} (which is needed for
example to explicate the semantics of if while etc)  Which is to say
the boolean type in python is not first class.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-14 Thread Steven D'Aprano
On Sat, 14 May 2011 00:45:29 -0700, rusi wrote:

 On May 14, 12:39 pm, Steven D'Aprano steve
 +comp.lang.pyt...@pearwood.info wrote:
 On Thu, 12 May 2011 23:46:12 -0700, rusi wrote:
  Mathematics has existed for millenia. Hindu-arabic numerals (base-10
  numbers) have been known for about one millennium The boolean domain
  is only a 100 years old. Unsurprisingly it is not quite 'first-class'
  yet: See
 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
  [Lifted fromhttp://c2.com/cgi/wiki?EqualVsTrueFalse]

 Th money-quote as regards using arbitrary objects in truth tests:

     [quote]
     All this changed with the introduction of the two-element boolean
     domain {true, false} which provides the vocabulary needed to
     assign values to boolean expressions: 34 is a way for writing
     true, 34 is a way for writing false, whereas the value of x0
     depends on the value of x ... [end quote]

 In Python, [1, 2, 3] is another way of writing true, and [] is another
 way of writing false. Similarly with any other arbitrary objects.
 
 Well so is [1,2] another way of writing True
 
 And then we get the interesting result that (True = True) is False

I presume you mean to say:

([1, 2] == True) is False

that is, that one true value is not equal to another true value.

That is correct. However, Python's == operator is not a Boolean Algebra 
operator. If it were, it would probably be called material 
biconditional, or XNOR, and written ↔ or - and would be smart enough 
to recognise that both [1, 2] and True are true.

Or possibly dumb enough... the difficulty is that the equality operator 
knows more about the objects than just their truth value.

And furthermore:

([1, 2] and True) == (True and [1, 2])

is also False, again because == is too smart to recognise that the left 
hand side (True) and the right hand side ([1, 2]) are both true values.

It's not that Python bools aren't first class objects, but that Python 
doesn't have a full set of all 16 possible boolean algebra operators.


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


Re: checking if a list is empty

2011-05-14 Thread Steven D'Aprano
On Sat, 14 May 2011 19:41:32 -0700, rusi wrote:

 The python entities: {True, False} are not an exact (isomorphic) model
 for the semantic boolean domain {true, false} (which is needed for
 example to explicate the semantics of if while etc)  Which is to say the
 boolean type in python is not first class.

I'm afraid I don't understand what you mean. Can you explain please, what 
properties of first class booleans do you think are missing from Python?



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


Re: checking if a list is empty

2011-05-13 Thread rusi
Mathematics has existed for millenia.
Hindu-arabic numerals (base-10 numbers) have been known for about one
millennium
The boolean domain is only a 100 years old.
Unsurprisingly it is not quite 'first-class' yet: See
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
[Lifted from http://c2.com/cgi/wiki?EqualVsTrueFalse ]


In retrospect, one might be tempted to regard the introduction of
something as simple as the boolean domain as a minor invention, but I
think that that would be a grave mistake: it is a great invention
because, being so simple, it is such a powerful simplifier. It is of
the same level as the introduction of natural numbers, which enabled
us to add 3 to 5, regardless of whether we are adding apples or
pears.

George Boole made a radical invention, so radical, in fact, that now,
more than a century later, the scientific community has not absorbed
it yet. (To stay with the metaphor: officially, boolean expressions
may have reached the status of first-class citizens, in practice —
because old habits and prejudices die hard— they are still the victims
of discrimination.) Let me give you a few examples.

In the programming language FORTRAN, as conceived a century after
Boole published his invention, boolean expressions are allowed, but
there are no boolean variables! Their introduction into programming
had to wait until the design of ALGOL 60.


So, M Harris problem is that python could almost be a language for the
'masses' (whatever that might mean) were it not for warts like l not
is empty is shorten-able to just l

Dijkstra's problem (paraphrased) is that python, by choosing the
FORTRAN alternative of having a non-first-class boolean type, hinders
scientific/mathematical thinking/progress.

I tend to agree with Dijkstra's view that the boolean type should be
given more respect
except for the small fact that the computer's ALU is based on the
logic-arithmetic pun:
half-adder = xor
(half)-carry = and
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-13 Thread Chris Rebert
On Thu, May 12, 2011 at 11:46 PM, rusi rustompm...@gmail.com wrote:
snip
 The boolean domain is only a 100 years old.
 Unsurprisingly it is not quite 'first-class' yet: See

It is nowadays. Every halfway-mainstream language I can think of has
an explicit boolean datatype. Heck, as of C99, even C has one now. I
conjecture the only languages still lacking one are exotic
niche/fringe languages. I would be interested to see a counterexample.

 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
 [Lifted from http://c2.com/cgi/wiki?EqualVsTrueFalse ]

 
 In retrospect, one might be tempted to regard the introduction of
 something as simple as the boolean domain as a minor invention, but I
 think that that would be a grave mistake: it is a great invention
 because, being so simple, it is such a powerful simplifier. It is of
 the same level as the introduction of natural numbers, which enabled
 us to add 3 to 5, regardless of whether we are adding apples or
 pears.

 George Boole made a radical invention, so radical, in fact, that now,
 more than a century later, the scientific community has not absorbed
 it yet. (To stay with the metaphor: officially, boolean expressions
 may have reached the status of first-class citizens, in practice —
 because old habits and prejudices die hard— they are still the victims
 of discrimination.) Let me give you a few examples.

 In the programming language FORTRAN, as conceived a century after
 Boole published his invention, boolean expressions are allowed, but
 there are no boolean variables! Their introduction into programming
 had to wait until the design of ALGOL 60.

 
 So, M Harris problem is that python could almost be a language for the
 'masses' (whatever that might mean) were it not for warts like l not
 is empty is shorten-able to just l

One language's wart is another language's idiom. And I think the
irrational hate towards syntactically-significant indentation is by
far a much larger barrier to mass adoption of Python; C++ has some
features that are at least (if not more) subtle/unobvious than
Python's __bool__(), yet it still enjoys mass use.

 Dijkstra's problem (paraphrased) is that python, by choosing the
 FORTRAN alternative of having a non-first-class boolean type, hinders
 scientific/mathematical thinking/progress.

Python has *not* chosen the Fortran alternative; *it has a first-class
Boolean type*, namely bool. This line of argument thus fails.
The fact that other types are implicitly coercible to bools doesn't
make `bool` itself any less first-class.

It is also ironic that one of the projects that exploits Python's
flexible typing regarding normally-Boolean operators is a scientific
one (NumPy).

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-13 Thread Hans Georg Schaathun
On Thu, 12 May 2011 23:20:20 +1000, Chris Angelico
  ros...@gmail.com wrote:
:  Writing a program requires expertise both in programming and in the
:  purpose for which it's being written. Ultimately, a programmer is a
:  translator; without proper comprehension of the material he's
:  translating, he can't make a clear translation. But that's completely
:  different from hiring someone to do a job, and then looking at the job
:  afterwards;

True.  When you are able completely to specify the job and commission 
it, then it is possible to isolate the disciplines, and reduce the
programmer to translator.

The challenge is that that very often is not the case.  

The double challenge in computing is that software its development 
is still not as well understood as hardware or construction.
We still do not have sufficient tools, experience and frameworks
to project and precisely plan a software development projects.
They go over time, over budget, and under specifications far more
often and more seriously than projects in other disciplines.
Civil and electronic engineers spend much of their time learning to
project and cost solutions.  Computer engineers very rarely do; they
just hack it.  In other trades, there tend to be clear role divisions
with different roles and specialisations, complementing eachothers.
We have not yet quite managed to work out what a programmer, architect,
designer, engineer, et cetera are in software.  We have the idea that
we need them, but we have not formalised them to the point where we
know what to expect from each role, and we struggle communicating
between them.

Therefore, a programmer is not just a translator.  The language to
specify precisely what is required is not good enough, and therefor
the programmer also needs to be a system designer, to some extent.
What extent depends much on the situation.

From my point of view, it is just harder to instruct a programmer
to write a code than it is to instruct a python interpreter.

:  if I order a concreting job, I'll look at whether it's
:  properly suited to the task, but I won't expect an explanation of
:  exactly what went into it, and I do not expect to understand the exact
:  chemistry of it. Only another expert in concrete would truly
:  comprehend it all.

Now you are thinking black and white, while reality is a gray blur.
You may not care about your concrete, but someone commissioning
concrete to build a skyscraper would surely want to check the
spec's to quite some level of detail.  The construction engineers
will surely need to know a lot more about the exact composition and 
science behind the recipe than the manager renting the top floor,
and still much less than the concrete engineer.

And the main difference here, is that the civil engineers have a much
better language to share information.  The best programmers have is
the programmming language, and we ought to make that as good as
possible.

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


Re: checking if a list is empty

2011-05-13 Thread rusi
On May 13, 1:02 pm, Chris Rebert c...@rebertia.com wrote:
 On Thu, May 12, 2011 at 11:46 PM, rusi rustompm...@gmail.com wrote:

  The boolean domain is only a 100 years old.
  Unsurprisingly it is not quite 'first-class' yet: See

 It is nowadays. Every halfway-mainstream language I can think of has
 an explicit boolean datatype.

I guess you did not quite see my 'quite' -- which itself is a
summarization of Dijkstra's officially vs in practice ? [Heres the
quote]


 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
  [Lifted fromhttp://c2.com/cgi/wiki?EqualVsTrueFalse]

  
  In retrospect, one might be tempted to regard the introduction of
  something as simple as the boolean domain as a minor invention, but I
  think that that would be a grave mistake: it is a great invention
  because, being so simple, it is such a powerful simplifier. It is of
  the same level as the introduction of natural numbers, which enabled
  us to add 3 to 5, regardless of whether we are adding apples or
  pears.

  George Boole made a radical invention, so radical, in fact, that now,
  more than a century later, the scientific community has not absorbed
  it yet. (To stay with the metaphor: officially, boolean expressions
  may have reached the status of first-class citizens, in practice —
  because old habits and prejudices die hard— they are still the victims
  of discrimination.) Let me give you a few examples.

  In the programming language FORTRAN, as conceived a century after
  Boole published his invention, boolean expressions are allowed, but
  there are no boolean variables! Their introduction into programming
  had to wait until the design of ALGOL 60.


As an analogy, in Perl, a list can get coerced to its length ... when
in scalar context.. or something like that.  Most programmers from
the static-typechecked-languages camp would balk at that laissez faire
attitude.  Likewise Harris is pointing out that noob python
programmers may feel a bit unnerved by non-boolean types unexpectedly
showing 'boolean-ness.'  Maybe we are just more in noob category and
we've not got the zen of python?? Dunno...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-13 Thread harrismh777

ru...@yahoo.com wrote:

http://www.codinghorror.com/blog/2006/07/separating-programming-sheep-from-non-programming-goats.html



A later paper by the same authors...
(http://www.eis.mdx.ac.uk/research/PhDArea/saeed/paper3.pdf)



These papers are fascinating reading, not only for philosophy sake in a 
great study in epistemology, but for a good clean study in good science 
and an appropriate measure of the scientific method in an interesting 
case study that 'failed'. In that regard it was a huge success!


The authors recognize (in paper [2]) that while their findings disproved 
their hypothesis the advances they made through good science have left 
the door open for further study. This is good news for the field of 
philosophy generally, and for epistemology in particular.


---

I too have noticed the general 'case' put forward in paper(1): namely, 
some people just don't seem to get it on the surface, and we can't 
figure out why.  On the other hand, I have 'always' been able to teach 
computer science (programming in particular) to 'anyone' given enough 
time, attention, creativity, and caring. In fact, when I find someone 
who is exhibiting low aptitude potential (let's say zero '0') then I 
must allow even more time, more attention, much more creativity, and a 
lot more caring.


I remember a line from Mr. Holland's Opus,  (a great movie, by the 
way) where Mr Holland is explaining to the coach why a certain young man 
has not any musical acumen --- and the coach says, ..you telling me you 
can't teach a willing kid to beat a drum...?... then you're a lousy 
teacher!  Holland ended up teaching us all a lot more than how to beat 
a drum, before the end of the movie


The point here is that aptitude says what a person has been conditioned 
for at this 'point in time' to be able to do... but says nothing about 
what re-conditioning might do for a transformed life! If I can't teach a 
kid how to program a computer, I'm a lousy teacher!


---

I grew up with computers. But kids today have 'magical' thinking about 
these machines, because they didn't grow up with them. If you started 
out (like I did) on the Altair 8800, or the Wang 700, programming in 
machine code, it became very clear rapidly why a high level language of 
some type might be beneficial ( and you could relate how the language 
constructs made the translation to machine code possible ). It was 
easier for me to learn programming, because I evolved with it.


On the other hand, kids today are dumped into a first comp sci course in 
programming and plopped in-front of a Hugs interactive shell and then 
are expected to learn programming and be successful by trying to grasp 
pure functional programming in Haskell(!) in a ten to 12 week term and 
we wonder why so many students are failing their 'first' programming 
class!!  Give me a break.  No, give them a break.


Guido van Rossum has said in one of his interviews (can't remember now 
which one) that BASIC is a terrible first computer language... and I 
agree... but, it was a lot better than Hugs!  But that's not my point, 
my point is that Python is better still.  Why?  Because Python can be 
taught at a *very* rudimentary level ( input, control, arithmetic, logic 
and output ) in almost a BASIC or REXX procedural style -- top down -- 
so that students 'get it'. Then, in subsequent classes down the road 
(much later) Python can grow and expand with the student's 
re-conditioning for more in-depth expansion of concepts and knowledge.


At the graduate level Python will still be there... challenging students 
to extend and expand in ways that were not even possible to discuss in 
the first introductory course. It seems to me that if the goal of comp 
sci courses at universities and colleges is 'education' that comp sci 
professors and instructors would get a handle on this.


If you can't teach a willing kid to write a functioning computer program 
then you're a lousy teacher.



kind regards,
m harris

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


Re: checking if a list is empty

2011-05-13 Thread Ian Kelly
On Fri, May 13, 2011 at 1:41 PM, harrismh777 harrismh...@charter.net wrote:
 On the other hand, kids today are dumped into a first comp sci course in
 programming and plopped in-front of a Hugs interactive shell and then are
 expected to learn programming and be successful by trying to grasp pure
 functional programming in Haskell(!) in a ten to 12 week term and we wonder
 why so many students are failing their 'first' programming class!!  Give me
 a break.  No, give them a break.

Well, at least Haskell is probably better as an introductory language
than Lisp or Scheme.  But what schools actually do this?  My
perception is that the vast majority of schools use C++ or C# or Java,
typically relegating functional programming to a single second- or
third-year course.  Of course it's well known that MIT used to use
Scheme, but they switched to Python a couple years ago.

 Guido van Rossum has said in one of his interviews (can't remember now which
 one) that BASIC is a terrible first computer language... and I agree... but,
 it was a lot better than Hugs!  But that's not my point, my point is that
 Python is better still.  Why?  Because Python can be taught at a *very*
 rudimentary level ( input, control, arithmetic, logic and output ) in almost
 a BASIC or REXX procedural style -- top down -- so that students 'get it'.
 Then, in subsequent classes down the road (much later) Python can grow and
 expand with the student's re-conditioning for more in-depth expansion of
 concepts and knowledge.

I don't think a single language is necessarily going to be best for
all students.  If a math major comes to you wanting to learn some
programming for theorem-proving, bearing in mind that they probably
aren't interested in learning more than a single language, would you
try to start them out with Python, or would you just give them the
functional language that they're ultimately going to want?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-13 Thread harrismh777

Ian Kelly wrote:

Well, at least Haskell is probably better as an introductory language
than Lisp or Scheme.  But what schools actually do this?


http://www.cs.kent.ac.uk/teaching/resources/haskell/HugsResources.html
http://research.cs.queensu.ca/home/cisc260/2010w/haskell.html

   These are just two schools that teach functional programming early 
on using Haskell... but there are many.  (google around)


   caveat:  thingks are changing all the time, for instance I notice 
that Margaret Lamb at Queen's University in Ontario hasn't updated her 
page in about a year... so things may be different there for her classes 
than when we were first corresponding...


  ... and I'm also lumping two other languages into this 'category'... 
namely, Scheme, and Erlang.



perception is that the vast majority of schools use C++ or C# or Java,


   ... that may be the trend now...


typically relegating functional programming to a single second- or
third-year course.  Of course it's well known that MIT used to use
Scheme, but they switched to Python a couple years ago.


Scheme seems to be very popular in education, based on the 
discussions, as a functional language; but, alas, I've not seen it nor 
played with it ( so can't comment too much, yet ).  I'm glad to hear 
that MIT is using Python now..!



I don't think a single language is necessarily going to be best for
all students.


   no doubt...   I can dream can't I ?


If a math major comes to you wanting to learn some
programming for theorem-proving, bearing in mind that they probably
aren't interested in learning more than a single language, would you
try to start them out with Python, or would you just give them the
functional language that they're ultimately going to want?


Well, that's just it... learning how to program is essential for all 
disciplines IMHO and learning just one language is not an option. 
Everyone needs a GPL and that's going to be Python... me hopes.  And 
then some majors are going to require special purpose languages that 
meet certain requirements... and functional languages (haskell, erlang, 
scheme) are going to suit that need very well) by the by, don't get me 
wrong... I think Haskell is elegant, one of the best... but, not for 
students with no programming background, nor for those who just don't 
seem to be getting it on the first pass.




kind regards,
m harris




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


Re: checking if a list is empty

2011-05-13 Thread Ian Kelly
On Fri, May 13, 2011 at 6:48 PM, harrismh777 harrismh...@charter.net wrote:
 Ian Kelly wrote:

 Well, at least Haskell is probably better as an introductory language
 than Lisp or Scheme.  But what schools actually do this?

 http://www.cs.kent.ac.uk/teaching/resources/haskell/HugsResources.html
 http://research.cs.queensu.ca/home/cisc260/2010w/haskell.html

   These are just two schools that teach functional programming early on
 using Haskell... but there are many.  (google around)

The first link is just a collection of Haskell resources, which
indicates that they use it, but not when.  They also have a collection
of Java resources on the department website.  Perusing the handbook, I
see the following modules:

CO320 Introduction to Object-Oriented Programming

This appears to be their introductory module.  It doesn't say what
language they use, but since they have Java resources on the website
that's what I'm going to guess.

CO530 Functional Programming

This is listed as an intermediate-level course and is in the 2nd/3rd
year handbook.  The synopsis includes: Introduction to a Haskell
system (sessions and scripts).  So no, Kent does not appear to be
teaching Haskell as an introductory course, or even in the first year.

The Queen's course also appears to be a 2nd year class, based on the
number.  Its description includes this: You will learn two new
languages: Haskell and Prolog. These languages are a bit different
from languages such as *Python* and *Java* that you have learned so
far in Queen's courses (emphasis added).  Notably, this class isn't
even focused on functional programming; it's an introduction to
programming paradigms other than the imperative one.

So far, neither of these universities support your claim that kids
today are dumped into a first comp sci course in programming and
plopped in-front of a Hugs interactive shell and then are expected to
learn programming and be successful by trying to grasp pure functional
programming in Haskell(!) in a ten to 12 week term.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-13 Thread Gregory Ewing

Ian Kelly wrote:

If a math major comes to you wanting to learn some
programming for theorem-proving, bearing in mind that they probably
aren't interested in learning more than a single language,


I would question whether theorem-proving is the *only*
thing they will ever want to do with a programming language.

If they really only want to learn one language, it would
be better to learn the one with the widest field of
applicability. I'd hazard to guess that writing a theorem
prover in Python would be a more practical proposition
than writing a script to automate processing his LaTeX
papers in Haskell.

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


Re: checking if a list is empty

2011-05-13 Thread Gregory Ewing

harrismh777 wrote:

  ... and I'm also lumping two other languages into this 'category'... 
namely, Scheme, and Erlang.


Scheme isn't really a functional language, though. You can
use a subset of it in a functional way, but it doesn't have
the sort of built-in support for pattern matching and case
analysis that true functional languages tend to have.

As families of languages go, Scheme has more in common with
Python than Haskell.

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


Re: checking if a list is empty

2011-05-13 Thread Gregory Ewing

rusi wrote:


Dijkstra's problem (paraphrased) is that python, by choosing the
FORTRAN alternative of having a non-first-class boolean type, hinders
scientific/mathematical thinking/progress.


Python doesn't have the flaw that Dijkstra was talking about.
Fortran's flaw wasn't so much the lack of a boolean type, but
that you couldn't assign the result of a logical expression to
a variable. Python has always been able to do that, even before
it had a distinct boolean type.

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


Re: checking if a list is empty

2011-05-13 Thread harrismh777

Ian Kelly wrote:

  Well, at least Haskell is probably better as an introductory language
  than Lisp or Scheme.  But what schools actually do this?




http://www.inf.ed.ac.uk/teaching/courses/inf1/fp/

http://www.cs.ou.edu/~rlpage/fpclassSpring97/


There are lots of these...   the two above afaik are still doing this at 
the entry level...... supposedly, these kids are 'mostly' successful 
and exit interviews are great...  but that doesn't fit with the observed 
idea that students are not doing well in comp sci classes generally... 
but, read below...  this at the entry level??


== block quote =
The first 10 to 11 weeks of the course use Haskell. Students are 
required to write nine programs in Haskell, three of which are team 
projects that combine software developed in individual projects. 
Different members of a team are assigned different individual projects, 
and the team efforts combine their solutions into a working piece of 
software.


In the early part of the course, students use operators like map, foldr, 
zip, and iterate to express computations. Explicit recursion is 
introduced after some experience with these common patterns of 
computation. Examples and problems address non-numeric applications, for 
the most part. Both interactive and file I/O are covered, but general 
purpose monads are not.


The last 5 to 6 weeks of the course use C, and most of the projects in 
that part of the course duplicate the function of earlier pieces of 
software that the students have written in Haskell.

== /block quote =
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On 11 May 2011 21:47:27 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  On Wed, 11 May 2011 20:13:35 +0100, Hans Georg Schaathun wrote:
:  One principle of object oriented programming is to bestow the objects
:  with properties reflecting known properties from the domain being
:  modelled.  Lists do not have truth values in the application domain
: 
:  Yes they do. Empty lists are nothing, ergo false, and non-empty lists are 
:  something, ergo true.

What application domain has established that terminology?

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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Wed, 11 May 2011 20:16:01 -0700 (PDT), alex23
  wuwe...@gmail.com wrote:
:  Hans Georg Schaathun h...@schaathun.net wrote:
:  Revolutionary indeed, so why don't we exploit the revolution
:  and write the programs to be as accessible as possible?
: 
:  Where do you draw the line, though?

I said that, as possible.  You draw it at the limit of possibility.

:  No decorators, as they're not intuitively obvious? No custom
:  descriptors, as that requires a deeper knowledge of Python internals
:  that utter ignorance allows?

When they help clarify or simplify the code, they are good.
When they do nothing of the sort, they aren't.

:  Both of those aspects alone seem far more complex and advanced than
:  treating empty collections as False.

Probably, but they also seem far more useful.

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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 17:44:07 +1200, Gregory Ewing
  greg.ew...@canterbury.ac.nz wrote:
:  Roy Smith wrote:
:  Hans Georg Schaathun h...@schaathun.net wrote:
: If both are numbers, they are converted to a common type. Otherwise, 
: objects of different types always compare unequal

Actually, I did not.
:-- hg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Steven D'Aprano
On Wed, 11 May 2011 22:53:45 -0500, harrismh777 wrote:

 alex23 wrote:
 through intuitive language skills.  Why not?
 Because the vast majority of them don't seem to want to be bothered?


 That could very well be... but I have a hope for them. I honestly think
 its not because they don't want to be bothered, rather they just think
 its too far past them...   and not do-able.

An admirable hope, but there is a significant amount of research into 
teaching computer programming that suggests that learning to program is 
simply beyond a large portion of the population, no matter what you do or 
what language you teach. Some 30-60% of people barely get past Hello 
World.

(That's not to imply that they're dumb, just that whatever mental skills 
are needed for programming is beyond them, just as whatever mental skills 
are needed for writing poetry are beyond me.)

http://www.codinghorror.com/blog/2006/07/separating-programming-sheep-from-non-programming-goats.html

Shorter version: it seems that programming aptitude is a bimodal 
distribution, with very little migration from the can't program hump 
into the can program hump. There does seem to be a simple predictor for 
which hump you fall into: those who intuitively develop a consistent 
model of assignment (right or wrong, it doesn't matter, so long as it is 
consistent) can learn to program. Those who don't, can't.



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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 01:49:05 -0400, D'Arcy J.M. Cain
  da...@druid.net wrote:
:  That's not programming.  That's using a canned app that a programmer
:  wrote that takes your unstructured input and does something useful with
:  it.  Spreadsheets are a primitive example of that.  Google is a more
:  advanced example.

You are really trying to defend the programmers' status as a modern
day priesthood, mastering a mystic art completely inaccessible to
those not initiated.  

For ages, the literate elite deliberately made the language cryptic
to protect their art and their status.  Some programmers seem to do
the same.

The fact is that it is not black and white.  There are programmers
with domain expertise, programmers without domain expertise, 
domain experts with decent programming skills, domain experts with
rudimentary programming skills, monolingual programmers, domain
experts without programming skills, polyglot programmers etc.

Only very narrow-purpose applications can be created by one of
these groups on their own, and to collaborate their abilities
must be overlapping.

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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On 11 May 2011 21:42:10 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  *Potentially* different tests. Which is exactly the point. Given an 
:  arbitrary object, the developer doesn't know what test is appropriate. 
:  Should I write len(x) == 0 or list(x) == [] or x.next is None or 
:  something else? How can I tell which is appropriate without knowing 
:  everything about the internals of every object I ever see?

Sure, but the question asked was how to check if a /list/ is empty.
You defend your answer assuming a different question.  You could
at least have the decency to change the subject header when you
go down that route.


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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
  wuwe...@gmail.com wrote:
:  On May 12, 7:24 am, harrismh777 harrismh...@charter.net wrote:
:  We need to move away from 'canned apps' to a new day where
:  the masses can sit down to their computer and solve new problems with it
:  through intuitive language skills.  Why not?
: 
:  Because the vast majority of them don't seem to want to be bothered?

Why does that matter?  There is a sizeable group who need computers
for purposes not (sufficiently) supported by the `canned apps'.
The fact that they are outnumbered by users who really only need
typewriters and entertainment theatres does in no way reduce the
need of those who actually need /computers/.

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


Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun h...@schaathun.net writes:

 On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
   wuwe...@gmail.com wrote:
 :  On May 12, 7:24 am, harrismh777 harrismh...@charter.net wrote:
 :  We need to move away from 'canned apps' to a new day where
 :  the masses can sit down to their computer and solve new problems with it
 :  through intuitive language skills.  Why not?
 : 
 :  Because the vast majority of them don't seem to want to be bothered?

 Why does that matter?  There is a sizeable group who need computers
 for purposes not (sufficiently) supported by the `canned apps'.

Those people, outnumbered by the masses as you say, are thereby not
themselves “the masses”.

-- 
 \  “Hey Homer! You're late for English!” “Pff! English, who needs |
  `\  that? I'm never going to England!” —Barney  Homer, _The |
_o__)Simpsons_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
  ben+pyt...@benfinney.id.au wrote:
:  Hans Georg Schaathun h...@schaathun.net writes:
: 
:  On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
:wuwe...@gmail.com wrote:
:  :  On May 12, 7:24 am, harrismh777 harrismh...@charter.net wrote:
:  :  We need to move away from 'canned apps' to a new day where
:  :  the masses can sit down to their computer and solve new problems with it
:  :  through intuitive language skills.  Why not?
:  : 
:  :  Because the vast majority of them don't seem to want to be bothered?
:  
:  Why does that matter?  There is a sizeable group who need computers
:  for purposes not (sufficiently) supported by the `canned apps'.
: 
:  Those people, outnumbered by the masses as you say, are thereby not
:  themselves “the masses”.

So what?  Do we only need solutions and systems for the masses?

What about systems for those who develop systems for the masses?
Or the theory necessary to develop the systems to develop more
advanced systems for the masses in the future?

Get real, software development and programming is more than just
overpriced web systems that just almost manage to replicate the 
functionality of IBM page based terminals and mainframes of 1973,
just slower and with more eye candy.

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


Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun h...@schaathun.net writes:

 On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
   ben+pyt...@benfinney.id.au wrote:
 :  Hans Georg Schaathun h...@schaathun.net writes:
 : 
 :  On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
 :wuwe...@gmail.com wrote:
 :  :  On May 12, 7:24 am, harrismh777 harrismh...@charter.net wrote:
 :  :  We need to move away from 'canned apps' to a new day where
 :  :  the masses can sit down to their computer and solve new problems with 
 it
 :  :  through intuitive language skills.  Why not?
 :  : 
 :  :  Because the vast majority of them don't seem to want to be bothered?
 :  
 :  Why does that matter?  There is a sizeable group who need computers
 :  for purposes not (sufficiently) supported by the `canned apps'.
 : 
 :  Those people, outnumbered by the masses as you say, are thereby not
 :  themselves “the masses”.

 So what?  Do we only need solutions and systems for the masses?

Your “why does that matter?” was addressed to an answer specifically in
the context of “a new day where the masses can sit down to their
computer and …”. The question is asked and answered.

If you want to raise a *new* topic – that of the non-masses who have
different needs – it's best not to start with “Why does that matter?”
but to lay out your separate case.

-- 
 \“Visitors are expected to complain at the office between the |
  `\ hours of 9 and 11 a.m. daily.” —hotel, Athens |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Roy Smith
In article 931adaf9g...@mid.individual.net,
 Gregory Ewing greg.ew...@canterbury.ac.nz wrote:

 Roy Smith wrote:
 If both are numbers, they are converted to a common type. Otherwise, 
 objects of different types always compare unequal
 
 That's just the default treatment for unrelated types that don't
 know anything about each other.
 
 I would guess that the list's == method is asking Is the
 other object a list?, and since a subclass of list is also
 a list, it's happy and goes on to compare the elements.

Well, that explains what's happening, but the behavior still doesn't 
match the docs.  Is this a bug or are the docs wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 4:21 PM, Hans Georg Schaathun h...@schaathun.net 
wrote:
 On Thu, 12 May 2011 01:49:05 -0400, D'Arcy J.M. Cain
  da...@druid.net wrote:
 :  That's not programming.  That's using a canned app that a programmer
 :  wrote that takes your unstructured input and does something useful with
 :  it.  Spreadsheets are a primitive example of that.  Google is a more
 :  advanced example.

 You are really trying to defend the programmers' status as a modern
 day priesthood, mastering a mystic art completely inaccessible to
 those not initiated.

Anyone can join. Not everyone wants to join. Me, I'm happy here as a
priest of the software industry, and I have no desire to become a
priest of, say, automotive engineering or concrete pouring. Would an
expert concreter be expected to explain to me exactly how to make
different sorts of concrete, or would he be expected simply to fulfill
his contract and provide me with my structure?

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


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 22:16:10 +1000, Chris Angelico
  ros...@gmail.com wrote:
:  Anyone can join. Not everyone wants to join. Me, I'm happy here as a
:  priest of the software industry, and I have no desire to become a
:  priest of, say, automotive engineering or concrete pouring. Would an
:  expert concreter be expected to explain to me exactly how to make
:  different sorts of concrete, or would he be expected simply to fulfill
:  his contract and provide me with my structure?

Of course he would.  When a piece of software to calculate the
properties or recipes for different kinds of concrete is needed.

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


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 10:43 PM, Hans Georg Schaathun h...@schaathun.net 
wrote:
 On Thu, 12 May 2011 22:16:10 +1000, Chris Angelico
  ros...@gmail.com wrote:
 :  Anyone can join. Not everyone wants to join. Me, I'm happy here as a
 :  priest of the software industry, and I have no desire to become a
 :  priest of, say, automotive engineering or concrete pouring. Would an
 :  expert concreter be expected to explain to me exactly how to make
 :  different sorts of concrete, or would he be expected simply to fulfill
 :  his contract and provide me with my structure?

 Of course he would.  When a piece of software to calculate the
 properties or recipes for different kinds of concrete is needed.

Writing a program requires expertise both in programming and in the
purpose for which it's being written. Ultimately, a programmer is a
translator; without proper comprehension of the material he's
translating, he can't make a clear translation. But that's completely
different from hiring someone to do a job, and then looking at the job
afterwards; if I order a concreting job, I'll look at whether it's
properly suited to the task, but I won't expect an explanation of
exactly what went into it, and I do not expect to understand the exact
chemistry of it. Only another expert in concrete would truly
comprehend it all.

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


Re: checking if a list is empty

2011-05-12 Thread Ethan Furman

Chris Angelico wrote:

On Thu, May 12, 2011 at 7:02 AM, Ian hobso...@gmail.com wrote:

In the real world  lists of zero items do not exist.
You don't go shopping with a shopping list of zero items.


Actually, yes you do. You maintain your shopping list between trips;
whenever you need something, you put it on the list immediately. Then
when you go shopping, you just take the list with you (if you're
lucky, you don't need to move or copy it at all, you just get another
reference to it). Once you're done, you empty the list - you now have
a shopping list with zero items (until you get home and realize you
forgot something).


Um -- you contradicted Ian, then contradicted yourself -- according to 
your scenario your shopping list is *not* empty when you go to the store 
(otherwise known as going shopping ;).


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


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Fri, May 13, 2011 at 12:02 AM, Ethan Furman et...@stoneleaf.us wrote:
 Chris Angelico wrote:

 On Thu, May 12, 2011 at 7:02 AM, Ian hobso...@gmail.com wrote:

 In the real world  lists of zero items do not exist.
 You don't go shopping with a shopping list of zero items.

 Actually, yes you do. You maintain your shopping list between trips;
 whenever you need something, you put it on the list immediately. Then
 when you go shopping, you just take the list with you (if you're
 lucky, you don't need to move or copy it at all, you just get another
 reference to it). Once you're done, you empty the list - you now have
 a shopping list with zero items (until you get home and realize you
 forgot something).

 Um -- you contradicted Ian, then contradicted yourself -- according to your
 scenario your shopping list is *not* empty when you go to the store
 (otherwise known as going shopping ;).

Ehh, mea culpa (I shouldn't post in haste). Replace Actually, yes you
do with Actually, yes they do. Indeed you do not *go shopping* with
a list of zero items; but a shopping list with no items on it DOES
exist (when you come back).

def do_shopping():
  if shopping_list:
goto shop; # Muahahahahaha.
for item in shopping_list:
  inventory.append(item)
return; # Muahahahaha again!

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


Re: checking if a list is empty

2011-05-12 Thread ru...@yahoo.com
On 05/12/2011 12:13 AM, Steven D'Aprano wrote:
[snip]
 http://www.codinghorror.com/blog/2006/07/separating-programming-sheep-from-non-programming-goats.html

 Shorter version: it seems that programming aptitude is a bimodal
 distribution, with very little migration from the can't program hump
 into the can program hump. There does seem to be a simple predictor for
 which hump you fall into: those who intuitively develop a consistent
 model of assignment (right or wrong, it doesn't matter, so long as it is
 consistent) can learn to program. Those who don't, can't.

A later paper by the same authors...
(http://www.eis.mdx.ac.uk/research/PhDArea/saeed/paper3.pdf)

Abstract:
[...] Despite a great deal of research into teaching methods
and student responses, there have been to date no strong
predictors of success in learning to program.  Two years ago
we appeared to have discovered an exciting and enigmatic new
predictor of success in a first programming course. We now
report that after six experiments, involving more than 500
students at six institutions in three countries, the predictive
effect of our test has failed to live up to that early promise.
We discuss the strength of the effects that have been observed
and the reasons for some apparent failures of prediction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Terry Reedy

On 5/11/2011 8:26 AM, Roy Smith wrote:


I conclude that li == [] should have returned False.  Either I'm not
understanding things correctly, or this is a bug.


The doc is wrong (and not only on this). I am working on a report with 
suggested fixes. Will post number when finish.


--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-12 Thread Terry Reedy

On 5/12/2011 3:37 PM, Terry Reedy wrote:

On 5/11/2011 8:26 AM, Roy Smith wrote:


I conclude that li == [] should have returned False. Either I'm not
understanding things correctly, or this is a bug.


The doc is wrong (and not only on this). I am working on a report with
suggested fixes. Will post number when finish.


http://bugs.python.org/issue12067

--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-12 Thread Steven D'Aprano
On Thu, 12 May 2011 07:36:27 -0400, Roy Smith wrote:

 In article 931adaf9g...@mid.individual.net,
  Gregory Ewing greg.ew...@canterbury.ac.nz wrote:
 
 Roy Smith wrote:
 If both are numbers, they are converted to a common type. Otherwise,
 objects of different types always compare unequal
 
 That's just the default treatment for unrelated types that don't know
 anything about each other.
 
 I would guess that the list's == method is asking Is the other object
 a list?, and since a subclass of list is also a list, it's happy and
 goes on to compare the elements.
 
 Well, that explains what's happening, but the behavior still doesn't
 match the docs.  Is this a bug or are the docs wrong?


The docs are incomplete.

You are missing two facts:

* The docs you are quoting refer only to built-in types. That it doesn't 
make so clear is a documentation bug.

* Talking about different and same types is ambiguous. It depends on 
how you compare types:

type(a) is type(b)

isinstance(a, type(b))

You are reading the docs as if the first comparison is the way to do it, 
but the second is usually preferred.

Any time you read something about the same type, you should mentally 
add (or an instance of a sub-class) to it, unless explicitly told 
different. Whether it is better to add that parenthetical comment every 
time it is needed, or to assume that the read knows enough about object-
oriented programming to assume it, is an open question.

Me personally, I think it's part of the mental landscape that can be 
assumed, like C docs might state dereference the pointer without adding 
(unless it is a nul pointer) *every single time*.


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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 07 May 2011 02:51:50 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  On Fri, 06 May 2011 14:57:21 -0700, scattered wrote:
: 
:  is there any problem with
:  
:  (3) if li == []:
:  
:  ?
:  
:  Seems to work when I test it and seems to clearly test what you are
:  trying to test. The only problem might be if in some contexts == has the
:  semantics of checking for object identity.
: 
:  Yes, if li == [] works too. But how do you know li is a list and not some 
:  other sequence type?

It says so in the Subject header :-)

:  The advantage of the if x test is that it is independent of the type of 
:  x.

Sure, but the question wasn't ...

The problem with 'if x' is that it requires a much more detailed 
understanding of python.  li == [] is as explicit as it gets, and
leaves no room for doubt.  len(li) == 0 is almost as explicit and
much more flexible.  Just x is as generic as it gets, but depends
on python's convolved rules for duck processing and if you aim at
legibility it is better avoided.


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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 07 May 2011 02:49:53 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  On Fri, 06 May 2011 16:05:09 -0400, Adam Tauno Williams wrote:
: 
:  I'd never accept code like if not x as an empty test.
: 
:  So much the worse for you then.
: 
:  The point of the if x idiom is that it is a polymorphic test which is 
:  independent of the type.

Normally, polymorphisms implies multiple forms only, where the different
forms has some form of common interpretation.  That's what makes
polymorphism useful and helpful, increasing legibility.

In this case, the interpretation of an arbitrary object as a boolean
is peculiar for python.  An empty list is a real, existing object, and 
the supposition that [] be false is counter-intuitive.  It can be
learnt, and the shorthand may be powerful when it is, but it will 
confuse many readers.

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


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens

In this case, the interpretation of an arbitrary object as a boolean
is peculiar for python.  An empty list is a real, existing object, and
the supposition that [] be false is counter-intuitive.  It can be
learnt, and the shorthand may be powerful when it is, but it will
confuse many readers.


Once I wrote something like:

def f(x=None):
   if x:
  print x
   else:
  print I have no value


The caller of that function was something like f(cos(2*theta)) where 
theta come from some computations.


Well. When it turned out that theta was equal to pi/4, I got I have no 
value. I spent a while to figure out the problem :)


Conclusion: the boolean value of an object is to be used with care in 
order to tests if an optional parameter is given or not (when default 
value is None).



Have a good noon
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Sat, 07 May 2011 21:57:13 -0700, Ethan Furman
  et...@stoneleaf.us wrote:
:  If you're going to use a language, and use it well, you have to learn 
:  how that language works.

And if the world evolves around the compiler and you, that advice
suffices.

However, programming is often as much about developing ideas in a large
and complex community, where perfect universal mastery of one language
is not an option, because half the community do not normally use that
language or aren't really programmers at all.  The less you assume about
the skill of the reader, the better it is.

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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 11:48:16 +0200, Laurent Claessens wrote:

 Once I wrote something like:
 
 def f(x=None):
 if x:
print x
 else:
print I have no value
 
 
 The caller of that function was something like f(cos(2*theta)) where
 theta come from some computations.
 
 Well. When it turned out that theta was equal to pi/4, I got I have no
 value. I spent a while to figure out the problem :)

I believe you are grossly oversimplifying whatever code you had. Using 
the definition of f from above:

 theta = math.pi/4
 f(math.cos(2*theta))
6.12303176911e-17

But even if you rounded the result of cos(2*theta) to zero, you will get 
the same result regardless of whether you test for if x or if x != 0.


 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).

Or, to put it another way: if you want to test for an object being None, 
test for the object being None.


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


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

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


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 10:02:42 +0100, Hans Georg Schaathun wrote:

 The problem with 'if x' is that it requires a much more detailed
 understanding of python.

Much more detailed? Hardly.

Understanding that Python accepts any and all objects in truth-testing 
concepts, and the rules thereof, is Python 101 territory. It's beginner-
level knowledge. It is far less advanced than the knowledge that ** is 
used for exponentiation. After all, many programmers have never needed to 
raise a number to a power, and might not learn about it for years, but 
every programmer writes if or while statements at some point.

Not knowing that you can write if x instead of if x == [] is like not 
knowing that you can write 

elif condition

instead of 

else:
if condition

If somebody were to argue that it is better to write else if explicitly, 
instead of the confusing elif, we'd all laugh at them.

Every time the question of conditional testing comes up here, it never 
ceases to astonish me how many developers argue against learning the 
idioms of the language, and prefer to re-use the idioms of other 
languages in Python.

Python is an object-oriented language where objects get to decide for 
themselves whether they should be treated as true or false. Writing:

if x == []:

instead of 

if x:

merely[1] because you worry that it isn't explicit enough, or could 
confuse other developers, or out of some nagging concern that maybe 
Python will do the wrong thing[2] unless you hold its hand through the 
process, is as silly as writing this:

count = 0
for item in x:
count += 1


instead of:

count = len(x)

(As silly, but not as verbose.)

I don't mean to insult anyone, but I've heard and read all the arguments 
against Python's truth-testing, and they don't impress me in the 
slightest. Most of them strike me as silly. The only argument that 
carries any weight to me is one which I haven't seen anyone raise:

if x: turns something which arguably could have been a mistake (oops, 
I forgot to write the condition!) into valid code.





[1]  It may be that there are good, solid reasons for writing explicit 
len(x)==0 tests, although I'm hard-pressed to think of any. The closest I 
come to is when you wish to emphasize equal to some number that just 
happens to be zero rather than it's a false/empty value. If so, you 
get a free pass to write the test the long way. E.g. you might write 
x % 2 == 1 rather than just x % 2 because you want to highlight that 
the remainder equals one, rather than the remainder merely being a true 
value.


[2]  Of course, a custom object x might misbehave when you test it for 
truth value. That would be a bug, just like it would be a bug if it 
misbehaved when you call len(x) == 0. If you can't trust if x to work, 
what makes you think you can trust len(x) == 0 either?


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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 10:14:38 +0100, Hans Georg Schaathun wrote:

 In this case, the interpretation of an arbitrary object as a boolean is
 peculiar for python.  

Incorrect. It is widespread among many languages. Programmers have been 
writing conditional tests using arbitrary values since 1958 when Lisp 
introduced the concept.

C, Forth and Visual Basic treat any non-zero number as true, and zero as 
false; that's not quite arbitrary objects, but it's arbitrary integer 
values. Similarly, Objective C has two different boolean types, BOOL 
which is a C char where 0 is false and everything else is true, and 
bool which is more like the Java boolean type.

Perl treats the empty string, 0, 0 and undefined variables as false, 
and everything else as true.

Ruby treats null and false as false, and everything else as true.

JavaScript treats , null, undefined, NaN, 0 and false as false values, 
and everything else as true.

PHP treats FALSE, 0, , 0, empty arrays, objects with no member 
variables, NULL, unset variables, and SimpleXML objects created from 
empty tags as false, everything else as true.

Clojure treats nil and false as false, everything else as true.

SQL's boolean type has three or four values: true, false, null and 
unknown, where implementations are free to treat null and unknown as 
either the same or different values. (So a 3 or 4 value logic, not 
actually Boolean at all.)

So Python is hardly unique, nor is this some new-fangled innovation.



 An empty list is a real, existing object, and the
 supposition that [] be false is counter-intuitive.

Not to me, nor to anyone who has an intuition about something versus 
nothing. I believe this distinction is fundamental to the universe, and 
that nearly every person understands this intuitively. The distinction 
between something and nothing is so strong that it took centuries of 
argument for the finest minds in Europe[1] to finally decide that, yes, 
zero is a number -- and they only did it because the Arabs and Indians 
had proven how useful it was, and Roman numerals really do suck for doing 
calculations.



 It can be learnt,
 and the shorthand may be powerful when it is, but it will confuse many
 readers.

In my experience, it does not confuse newbies or beginners. The only 
people it confuses are those who are over-educated into thinking that the 
One Correct Way of doing truth testing is with a dedicated boolean type, 
and anything else is heresy.


[1] At least is you asked them.


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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 11:47:42 +0100, Hans Georg Schaathun wrote:

 On Sat, 07 May 2011 21:57:13 -0700, Ethan Furman
   et...@stoneleaf.us wrote:
 :  If you're going to use a language, and use it well, you have to learn
 :  how that language works.
 
 And if the world evolves around the compiler and you, that advice
 suffices.
 
 However, programming is often as much about developing ideas in a large
 and complex community, where perfect universal mastery of one language
 is not an option, because half the community do not normally use that
 language or aren't really programmers at all.  The less you assume about
 the skill of the reader, the better it is.

Do you think that we should avoid chained comparisons, class methods, 
closures, co-routines, decorators, default values to functions, 
delegation, doc tests, exceptions, factory functions, generator 
expressions, inheritance, iterators, list comprehensions, operator 
overloading, properties, regular expressions, tuple unpacking, or unit 
tests, to say nothing of *advanced* techniques like descriptors or 
metaclasses, just in case the person reading your code is a clueless n00b?

We routinely and uncontroversially use all of these techniques (well, 
sometimes metaclasses get a few raised eyebrows). Truth testing is MUCH 
simpler than any of those.

It is extremely patronizing to say that we should avoid truth-testing 
arbitrary objects because it is too complicated for other people. It's 
not hard, and they can learn.



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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 13:36:02 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  In this case, the interpretation of an arbitrary object as a boolean is
:  peculiar for python.  
: 
:  Incorrect. It is widespread among many languages. Programmers have been 
:  writing conditional tests using arbitrary values since 1958 when Lisp 
:  introduced the concept.

The fact that you need to list language by language which objects
evaluate as false or equivalent to false illustrates that this has
to be learnt language by language.  Allowing arbitrary objects is
one thing, the particular interpretation is peculiar.

The fact that if and while accepts any object for the condition may
be chapter 1 stuff, but the memorisation of exactly how the
interpretation does not come early (unless you learn it by rote of
course).

:  C, Forth and Visual Basic treat any non-zero number as true, and zero as 
:  false; that's not quite arbitrary objects, but it's arbitrary integer 
:  values. Similarly, Objective C has two different boolean types, BOOL 
:  which is a C char where 0 is false and everything else is true, and 
:  bool which is more like the Java boolean type.

Mentioning C, with no Boolean type at all, in this context is a bit
absurd.  Understanding boolean evaluation in C is very little help
when you want to understand it in python.

:  An empty list is a real, existing object, and the
:  supposition that [] be false is counter-intuitive.
: 
:  Not to me, nor to anyone who has an intuition about something versus 
:  nothing. I believe this distinction is fundamental to the universe, and 
:  that nearly every person understands this intuitively. The distinction 
:  between something and nothing is so strong that it took centuries of 
:  argument for the finest minds in Europe[1] to finally decide that, yes, 
:  zero is a number -- and they only did it because the Arabs and Indians 
:  had proven how useful it was, and Roman numerals really do suck for doing 
:  calculations.

Exactly.  By now we have gotten past that old-fashioned idea that 0
is not a number.  Computer scientists even tend to count 0 as a
natural number.  When 0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.

:  In my experience, it does not confuse newbies or beginners. The only 
:  people it confuses are those who are over-educated into thinking that the 
:  One Correct Way of doing truth testing is with a dedicated boolean type, 
:  and anything else is heresy.

What kind of beginners are you talking about?  Beginners to python
or beginners to programming.

The audience I am concerned about is the ones who are over-educated 
into using and having used a score of different meanings of the same
symbols.  They will be used to their intuition being wrong when they
move into a new context.  Being explicit will help them.


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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 12:14:46 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  Not knowing that you can write if x instead of if x == [] is like not 
:  knowing that you can write 
: 
:  elif condition
: 
:  instead of 
: 
:  else:
:  if condition

My concern was with the reader and not the writer.

What could elif mean other than else: if?

if x could, for instance,  mean if x is defined.


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


Re: checking if a list is empty

2011-05-11 Thread D'Arcy J.M. Cain
On Wed, 11 May 2011 11:47:42 +0100
Hans Georg Schaathun h...@schaathun.net wrote:
 However, programming is often as much about developing ideas in a large
 and complex community, where perfect universal mastery of one language
 is not an option, because half the community do not normally use that
 language or aren't really programmers at all.  The less you assume about
 the skill of the reader, the better it is.

Non-programmers should be able to program?

Should non-doctors be able to doctor?  Should cars be built so that
anyone can intuitively fix them without a mechanic?  Should trucks be
built so that drivers don't have to learn how to split shift?  Why is
programming so different that we can't expect people to actually learn
their discipline?

This discussion is giving me some insight into some of the crap
programming I see these days.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread D'Arcy J.M. Cain
On Wed, 11 May 2011 15:05:45 +0100
Hans Georg Schaathun h...@schaathun.net wrote:
 What could elif mean other than else: if?

If run by an elf?  Who knows.  You do, of course, if you have learned
the basics of the language you are using.

 if x could, for instance,  mean if x is defined.

It could also mean if x was created on a Tuesday.  A short
introduction to the language explains what it actually means.

When did we come to the idea that people should be able to program in a
language without actually learning it?  The fact that Python comes so
close to that possibility is nothing short of revolutionary.  I suppose
one day a reasoning android will be able to sit down at the terminal of
a star ship computer and ask simple questions while making random hand
movements across a screen but for now I am afraid that programmers
still have to learn programming.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 13:45:52 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  Do you think that we should avoid chained comparisons, class methods, 
:  closures, co-routines, decorators, default values to functions, 
:  delegation, doc tests, exceptions, factory functions, generator 
:  expressions, inheritance, iterators, list comprehensions, operator 
:  overloading, properties, regular expressions, tuple unpacking, or unit 
:  tests, to say nothing of *advanced* techniques like descriptors or 
:  metaclasses, just in case the person reading your code is a clueless n00b?

Not at all.  On both accounts.
1. My concern was not about clueless newbies.  They need to
  learn.  My concern is about experienced scientists and engineers 
  who are simply new to python.  They will be dealing with a dozen
  different languages (programming and otherwise), with a need to
  read more languages than they can possibly learn to master.

2. You should avoid constructs which can /reasonably/ be avoided to 
  /increase/ legibility.  Writing if x for if len(x)  0 when you
  know that x is of some sort of collection type with len defined
  does nothing to help legibility.  Many of the socalled advanced
  constructs you mention are used to increase legibility one way or
  another.  Others will simply allow functionality which would otherwise
  be impossible.

  I don't object to using if x in a case where x may or may not have
  len() defined.

:  We routinely and uncontroversially use all of these techniques (well, 
:  sometimes metaclasses get a few raised eyebrows). Truth testing is MUCH 
:  simpler than any of those.

Simpler, yes, but it surely depends on more detailed knowledge.  One has
to remember how the boolean conversion works, for each possible data type.
This requires looking up the rules for each data type.

E.g. Anyone who has used list/set comprehension in Z, haskell, set theory,
or whereever will understand python list comprehension immediately.

:  It is extremely patronizing to say that we should avoid truth-testing 
:  arbitrary objects because it is too complicated for other people. It's 
:  not hard, and they can learn.

Again you miss the point.  It is not /too/ complicated.
It is /unnecessarily/ complicated.  You don't noticeably
gain anything by using if x instead of if len(x)  0, if
you know that the latter is defined.  

If everyone who ever needs to see your program is a python
programmer, then your approach works as well as mine.  

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


Re: checking if a list is empty

2011-05-11 Thread Chris Angelico
On Thu, May 12, 2011 at 12:00 AM, Hans Georg Schaathun h...@schaathun.net 
wrote:
 The fact that you need to list language by language which objects
 evaluate as false or equivalent to false illustrates that this has
 to be learnt language by language.  Allowing arbitrary objects is
 one thing, the particular interpretation is peculiar.

Languages have to be learned language by language. Yes, you want to be
similar to others if you can (and in 'most every language where it's
legal syntax, 1+2 will mean 3), but whenever I'm working in a
language with which I'm not _really_ fluent, I like to keep an
operator table handy (precedence, plus oddments like what the
exponentiation operator is, or whether  is bitwise or boolean). They
do differ, and if I'm writing in PHP or Python or Pike or C++ or Java
or whatever else it be, I have to use the operators the way the
interpreter/compiler will understand them, not in some other way that
I deem better.

 Mentioning C, with no Boolean type at all, in this context is a bit
 absurd.  Understanding boolean evaluation in C is very little help
 when you want to understand it in python.

Actually, it's not.

# Python code:
if x:
 statements

/* C code: */
if (x) {
 statements;
}

What's the difference? Both of them let you test the truth of some
arbitrary object or expression, and neither of those statements
implies a Boolean type. In C++, this is exploited extensively with,
for instance, the stream I/O objects evaluating as false when in an
error or EOF state:

while (infile) infile  *ptr++; // Compact and convenient way to read
into an array

Actually that one can be combined down even further, but for clarity I
leave it like that.

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


Re: checking if a list is empty

2011-05-11 Thread Redcat
On Wed, 11 May 2011 10:33:51 -0400, D'Arcy J.M. Cain wrote:

 Non-programmers should be able to program?

Wasn't that sort of the premise behind Visual Basic? I don't know if that 
was the intention, but it sure was the result in a lot of cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Ethan Furman

Hans Georg Schaathun wrote:

On 11 May 2011 13:36:02 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  In this case, the interpretation of an arbitrary object as a boolean is
:  peculiar for python.  
: 
:  Incorrect. It is widespread among many languages. Programmers have been 
:  writing conditional tests using arbitrary values since 1958 when Lisp 
:  introduced the concept.


The fact that you need to list language by language which objects
evaluate as false or equivalent to false illustrates that this has
to be learnt language by language.  Allowing arbitrary objects is
one thing, the particular interpretation is peculiar.



Like so many other things Python got right, I think it got this right as 
well.  something vs nothing is simple, useful, and easy to remember.




By now we have gotten past that old-fashioned idea that 0
is not a number.  Computer scientists even tend to count 0 as a
natural number.  When 0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.


Python is not concerned with whether it exists -- that's a name binding; 
 Python is concerned with whether anything is there.  0 apples is 
nothing and a an empty list is nothing as well.


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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 15:05:45 +0100, Hans Georg Schaathun wrote:

 My concern was with the reader and not the writer.
 
 What could elif mean other than else: if?

It could mean Oh, the author has made a stupid typo, I better fix it.

It could mean What does the elif command do?

The first time I read Python code, I had literally no idea what to make 
of elif. It seemed so obvious to me that any language would let you write 
else if ... (on a single line) that I just assumed that elif must be 
some other construct, and I had no idea what it was. It never even 
crossed my mind that it could be else if rammed together into one word.

I soon learned better though.

Once you start dumbing down your code for readers who don't know your 
language, it's a race to the bottom. There's very little you can write 
that *somebody* won't misunderstand.



 if x could, for instance,  mean if x is defined.

Yes it could, if you're programming in Perl. But we're not.

When I write a sentence in English, and I use the word gift to mean a 
thing which is given, I don't worry that German or Swedish readers will 
think I'm talking about poison. If I use preservative, I mean something 
which preserves, and if Italian and Spanish readers mistake it for a 
condom, that's their problem, not mine. Writing code is no different. 
When I'm coding in Python, I use Python rules and meanings, not some 
other language.

Why should I code according to what some hypothetical Python dummy 
*might* think the code will do, instead of what the code *actually* does?



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


Re: checking if a list is empty

2011-05-11 Thread Chris Angelico
On Thu, May 12, 2011 at 1:50 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Wed, 11 May 2011 15:05:45 +0100, Hans Georg Schaathun wrote:

 My concern was with the reader and not the writer.

 What could elif mean other than else: if?

 The first time I read Python code, I had literally no idea what to make
 of elif. It seemed so obvious to me that any language would let you write
 else if ... (on a single line) that I just assumed that elif must be
 some other construct, and I had no idea what it was. It never even
 crossed my mind that it could be else if rammed together into one word.

In a Bourne shell script, if ends with fi... case ends with esac... so
file would end with... hmm. Yeah, I think it's best to know the
language you're trying to comprehend, and/or actually look at context
instead of shoving a piece of code under someone's nose and saying I
bet you can't figure out what THIS does!.

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


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 15:34:28 +0100, Hans Georg Schaathun wrote:

 On 11 May 2011 13:45:52 GMT, Steven D'Aprano
   steve+comp.lang.pyt...@pearwood.info wrote:
 :  Do you think that we should avoid chained comparisons, class methods,
 :  closures, co-routines, decorators, default values to functions, : 
 delegation, doc tests, exceptions, factory functions, generator : 
 expressions, inheritance, iterators, list comprehensions, operator : 
 overloading, properties, regular expressions, tuple unpacking, or unit :
  tests, to say nothing of *advanced* techniques like descriptors or : 
 metaclasses, just in case the person reading your code is a clueless
 n00b?
 
 Not at all.  On both accounts.
 1. My concern was not about clueless newbies.  They need to
   learn.  My concern is about experienced scientists and engineers who
   are simply new to python.

Which makes them clueless newbies *about Python*. I don't care how 
experienced they are in astrophysics or biology or calculating the 
average airspeed of an unladen swallow.


   They will be dealing with a dozen different
   languages (programming and otherwise), with a need to read more
   languages than they can possibly learn to master.

Yeah, life is hard and then you die, and scientists don't even get paid 
that much. So what? Do physicists write their scientific papers about 
string theory with the thought What if some Python programmer who knows 
nothing about string theory is reading this? I better dumb it down.

Of course not. A ridiculous idea. They use their tools the way they are 
designed to be used, and outsiders have to learn the language and the 
jargon to make sense of it. This is not a problem that needs solving.

It's one thing to simplify code that you are explicitly using as a 
teaching aid. That's a good thing, I approve of that. But it's a 
completely different thing to dumb down production code because you think 
some non-programmer might have to read it.



 2. You should avoid constructs which can /reasonably/ be avoided to
   /increase/ legibility.  Writing if x for if len(x)  0 when you know
   that x is of some sort of collection type with len defined does
   nothing to help legibility.

Of course it does. 

It means you don't have to care about implementation details of what 
emptiness means for a list. It means you don't force the reader to read, 
parse and understand three extraneous terms. It means you don't force the 
reader to wonder why you bothered to use a long-winded test when a short 
test would do, or be concerned that maybe  0 is a typo and you actually 
meant  10.


[...]
 Simpler, yes, but it surely depends on more detailed knowledge.  One has
 to remember how the boolean conversion works, for each possible data
 type. This requires looking up the rules for each data type.

No. You have that exactly backwards. The point of if x is that you 
DON'T have to care about how the boolean conversion works, because the 
object itself encapsulates that behaviour. This is basic object-oriented 
principles.

When you call len(x) you don't care about the details of how to calculate 
the length of x. The object itself knows so that you don't have to. The 
same applies to truth testing.

I have a data type that is an array of lists. When you call if len(x)  
0 on it, it will blow up in your face, because len(x) returns a list of 
lengths like [12, 0, 2, 5]. But if you say if x, it will do the right 
thing. You don't need to care how to truth-test my data type, because it 
does it for you. By ignoring my type's interface, and insisting on doing 
the truth-test by hand, you shoot yourself in the foot.



 E.g. Anyone who has used list/set comprehension in Z, haskell, set
 theory, or whereever will understand python list comprehension
 immediately.

Yes. And anyone who hasn't, probably won't. But they will learn.



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


Re: checking if a list is empty

2011-05-11 Thread Ian Kelly
On Wed, May 11, 2011 at 8:34 AM, Hans Georg Schaathun h...@schaathun.net 
wrote:
 E.g. Anyone who has used list/set comprehension in Z, haskell, set theory,
 or whereever will understand python list comprehension immediately.

They would understand the underlying concept.  But would somebody who
is not a Python programmer intuitively understand the difference
between this:

[x + 3 for x in xs if x % 2 == 1]

and this:

{x + 3 for x in xs if x % 2 == 1}

and this:

(x + 3 for x in xs if x % 2 == 1)

Somebody with rudimentary Python knowledge might even reason that
since the first two create a list and a set respectively, the third
must therefore create a tuple, which is wrong.

None of this should be taken as an argument against using generator expressions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Eric Snow
All of this just boils down to Python providing an implicit bool cast in
syntactic situations that expect conditional expressions, including if [1].
 So if x: is equivalent to if bool(x).  Perhaps that is the part that is
not immediately obvious, being implicit to Python conditional syntax.

Python also provides a mechanism for customization of a wide variety of
behavior that is not obvious without reading the [excellent] documentation
[2].  So the following three forms will implicitly call the special method
names:

if x:  =  if bool(x):  =  if x.__bool__():  [3]

if x == []:  =  if x.__eq__([]):

if len(x) == 0:  =  if x.__len__() == 0:

Other than the implicit cast to bool for conditional syntax and the implicit
calls to special method names as appropriate I am not clear that there is
any remaining mystery for this question.  And the language reference makes
all of the above very clear, so I highly recommend it.

The only caveat is that builtin types don't always act the same way as user
defined types (classes).  Not sure if the few differences are well
documented, but to be honest that hasn't bit me hard enough that I needed to
look it up.  I do know that the builtin list has a __eq__ method and a
__len__ method, but not a __bool__ method (which it doesn't need [3]).

-eric

[1]
http://docs.python.org/dev/py3k/reference/compound_stmts.html#the-if-statement
[2]
http://docs.python.org/dev/py3k/reference/datamodel.html#special-method-names
[3] http://docs.python.org/dev/py3k/reference/datamodel.html#object.__bool__
so if __bool__ doesn't exist it tries __len__ and so forth.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
 I don't mean to insult anyone, but I've heard and read all the arguments 
 against Python's truth-testing, and they
don't impress me in the slightest. Most of them strike me as silly. The only 
argument that carries any weight to me is
one which I haven't seen anyone raise:

if x: turns something which arguably could have been a mistake (oops, I 
forgot to write the condition!) into valid
code.

The only problem I have had with the if x: notation is when I have values 
that might be empty lists, empty strings, None, or a boolean value being 
returned from the same source. But this is probably an instance when a good 
programmer would explicitly check the type instead of the naive if x: 
notation.

On the other hand, as a fairly n00b Python (and n00b Perl) developer, I find 
the notation if not x: to be far more English readable than if x==None or 
len(x)== 0 or x==0 or bool(x): (or some derivative/combination of those). 



Ramit

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase  Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase 
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
The audience I am concerned about is the ones who are over-educated 
into using and having used a score of different meanings of the same
symbols.  They will be used to their intuition being wrong when they
move into a new context.  Being explicit will help them.

I find this argument to be flawed. Should I stop using built-in generators 
instead of range/xrange for looping through lists? Certainly for loops with 
loop counting are understood more widely than generators. Should I stop using 
any advanced feature Python because it is difficult to understand without 
knowing Python?

I do not code for absolute beginner in Python to read my code. That way lies 
madness! I code with the assumption that someone with intermediate knowledge 
can read my code (unless I am forced into optimizing and then I rely on 
comments to explain). Actually, that is how I attempt to code in any language.

I may not have made the point well, but I cannot see any advantage for trying 
to program for the lowest common denominator.


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase  Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase 
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:33:51 -0400, D'Arcy J.M. Cain
  da...@druid.net wrote:
:  Non-programmers should be able to program?

That was not really what I suggested; I was primarily talking
about reading programs and commenting on formulæ and algorithms.

:  Should non-doctors be able to doctor?

If I were God, I might consider simplifying the anatomy to allow that,
yes.

:Should cars be built so that
:  anyone can intuitively fix them without a mechanic?  Should trucks be
:  built so that drivers don't have to learn how to split shift?

That's out of my area so I don't know.  However, contrary to
software, I have never seen any use of rebuilding the car to
do something other than transport ...

And, besides, as mechanics do not design cars or even engines, they 
are not analogous to programmers, but rather to computer technicians 
(maintenance, deployment, installation, etc).

: Why is
:  programming so different that we can't expect people to actually learn
:  their discipline?

It is not different from other engineering disciplines, where you would
have to interact with experts from other disciplines, and understand
and comment on their designs.  That's the way to build a /system/.

Say, you want to create the software to make weather forcasts.
At the end of the day, that's programming, but no way that's going
to be a task for programmers alone.  You need mathematicians,
algorithm theorists, physicists, programmers, and multiple 
specialisations within each discipline.  If you can make your 
programs clear enough to be used as a language of communications, 
you will simplify the development, and allow the code to be
validated by those who knows how the computation has to be done
without specialising in talking to the computer.

:  This discussion is giving me some insight into some of the crap
:  programming I see these days.

I wonder if you would do a better job at programming the software
to crack equations from quantum physics than the physicist :-)

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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 16:26:40 GMT, Steven D'Aprano
  steve+comp.lang.pyt...@pearwood.info wrote:
:  1. My concern was not about clueless newbies.  They need to
:learn.  My concern is about experienced scientists and engineers who
:are simply new to python.
: 
:  Which makes them clueless newbies *about Python*. I don't care how 
:  experienced they are in astrophysics or biology or calculating the 
:  average airspeed of an unladen swallow.

Someone who knows how to program is never clueless starting a new
language.  Newbie, may be, but he knows most of the constructions
and semantic principles to look for; most of it is learning the syntax.

:  Yeah, life is hard and then you die, and scientists don't even get paid 
:  that much. So what? Do physicists write their scientific papers about 
:  string theory with the thought What if some Python programmer who knows 
:  nothing about string theory is reading this? I better dumb it down.

That depends on the purpose of that particular paper, but the real 
question is, who writes the software to test that string theory 
empirically?  Please tell.

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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Thu, 12 May 2011 02:05:21 +1000, Chris Angelico
  ros...@gmail.com wrote:
:  In a Bourne shell script, if ends with fi... case ends with esac... so
:  file would end with... hmm. Yeah, I think it's best to know the
:  language you're trying to comprehend, and/or actually look at context
:  instead of shoving a piece of code under someone's nose and saying I
:  bet you can't figure out what THIS does!.

Code is quite often published to document algorithms, methods and
formulæ for the purpose of scientific research.  Since there is no
universal language which suits everything and everyone, this
is exactly what happens.  One has to have the rudimentary knowledge
to read half a dozen different languages to be able to read the
code and extract the algorithms.  If one tried to maintain the
necessary programming skills to exploit all of those languages to
their full potential, one would simply not be able to keep up with
the application discipline.

If all you do is to write software for computer illiterate users, YMWV.

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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:27:49 -0400, D'Arcy J.M. Cain
  da...@druid.net wrote:
:  When did we come to the idea that people should be able to program in a
:  language without actually learning it?  The fact that Python comes so
:  close to that possibility is nothing short of revolutionary.

Revolutionary indeed, so why don't we exploit the revolution
and write the programs to be as accessible as possible?

(Although, python is not the most revolutionary in this respect.)

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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:31:59 -0600, Ian Kelly
  ian.g.ke...@gmail.com wrote:
:  (x + 3 for x in xs if x % 2 == 1)

Interesting.  Thanks.  That might come in handy some time.

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


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 13:50:54 -0400, Prasad, Ramit
  ramit.pra...@jpmchase.com wrote:
:  I find this argument to be flawed. Should I stop using built-in 
: generators instead of range/xrange for looping through lists?
: Certainly for loops with loop counting are understood more widely
: than generators. Should I stop using any advanced feature Python
: because it is difficult to understand without knowing Python?

No; I'd suggest the most legible and intuitive construct that /does/ the
job.  Never something which requires one extra (illegible) page to do
the job, or something which does not do the job at all.

:  I may not have made the point well, but I cannot see any advantage 
: for trying to program for the lowest common denominator.

Common to what?  I'd try the lowest common denominator of
legibility and effictiveness.

It is just KISS.

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


  1   2   >