Re: if the else short form

2010-10-13 Thread John Nagle

On 10/10/2010 6:46 PM, Lawrence D'Oliveiro wrote:


Languages that insisted on being able to do proper compiler-level cross
checks between separately-compiled modules (e.g. Modula-2, Ada) never really
became that popular. This saddened me.


   It's an sad consequence of a UNIX mindset that you can't change
the linker.  This stems from the early days of UNIX, where the
linker was in assembler, very limited, and had very few
comments.  That's why C++ had name mangling, instead of
a type-aware linker.  Really.

   There are interesting things to do at link time, and the Gnu
toolchain finally added some of them.  Weak links, for example -
ones which are resolved if the target is present, but won't
pull it in. This allows bringing in C++ classes without
hauling in every unreferenced member function of the class.

   Modula did more at link time.  In Modula, modules had
initialization sections.  Initialization sections could call
functions in other modules.   The rule was that you couldn't call
into a module until the module's initialization section had run.
Conveniently, the Modula binder computed the dependency graph
of what called what, and ordered the initialization sections so
that all modules were initialized before being called.  The
binder could detect dependency loops, and reported them at
link time.  So if the program would build, it would initialize
in proper order.

   This is a nice check, because it's a global property of
the program, not a local bug.  It's the sort of thing that
appears on large projects where different people are doing
different modules.  Computers are better than
people at finding that class of problem.

   C++ got this wrong, leading to the static initialization
order fiasco.  Python is vulnerable to this problem in
import loops, although the consequences aren't as severe as
in C++.

John Nagle

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


Re: if the else short form

2010-10-11 Thread Neville Dempsey
On Oct 11, 11:46 am, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 Nowadays we take it for granted that the core language should be a strong
 and compact basis to build on, rather than providing lots of built-in
 features, and all the rest should come from run-time libraries.

Fast forward to 1972...
In 1972 British Military implemented USE, KEEP and HERE for ALGOL 68RS

and then in 1978...

Check out NEST and EGG in Formal Definition of Modules and Separate
Compilation.
http://www.google.com.au/search?q=%22A-Modules-and-Separate-Compilation-facility-for-ALGOL-68%22

9.4.1.d
   module symbol{49a}   MODULE
   access symbol{36b}   ACCESS
   def symbol{49c}  DEF
   fed symbol{49c}  FED
   public symbol{36d,41e}   PUB
   postlude symbol{49f} POSTLUDE
{{Moreover, two more new symbols are yet to be invented for use in
separate compilation:}}
   formal nest symbol{56b}  NEST
   egg symbol{A6a,c}EGG

These were defined to avoid things like C's problem with #include
For example a typical 5 line program can require the compilation of a
163kb file, 5 linesor original source becomes almost 5 thousand lines
of pre-processed source e.g.:

$ cat hello_world.c
#include stdlib.h
#include stdio.h
int main(int c, char *argv, char *argp){
  printf(Hello, world!\n);
}
$ gcc -C -E hello_world.c -o hello_world.txt
$ wc hello_world.txt
  4554  24360 163915 hello_world.txt

The idea would be to compile the text file one and generate one
compiled file contains the required symbols... bingo, there you have
it.  Compilations are potentially 1000x faster?  Hence the NEST and
EGG idea.

The Soviet GOST standard details the standardisation of NEST and EGG
(Page 271):
http://vak.ru/lib/exe/fetch.php/book/gost/pdf/gost-27975-88.pdf
(altogether there are also: MODULE, ACCESS, DEF, FED, PUB, POSTLUDE,
NEST  EGG)

(BTW: The Soviet standard also details the use of ON, EXCEPTION and
RAISE, on page 269)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-10 Thread saeed.gnu
 True == 1
True
 False == 0
True
 int(True)
1
 int(False)
0
 bool(1)
True
 bool(0)
False


‌But:
str(fill==True)+','
is simpler than:
(False,, True,)[fill==True]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-10 Thread Lawrence D'Oliveiro
In message
45368e8d-3b4f-4380-974d-bf9cd5d68...@w9g2000prc.googlegroups.com, 
NevilleDNZ wrote:

 I do ponder why (given that linked lists can easily be created in Algol68)
 useful types like LIST and DICT were left out of the standard prelude.

I guess a list type wasn’t seen as primitive enough. Besides, what would you 
call the fields—would you use the LISP-traditional names of “car” and “cdr”? 
POP-2, another language from that time, used “hd” and “tl”, but these were 
actually functions that looked for fields named “front” and “back”, and 
interpreted their values in special ways. This allowed for “lazy 
evaluation”, which meant that list elements only took up storage when they 
were actually referenced.

As for DICT, I think table lookups were still a sufficiently novel concept 
for people to disagree on how they should best be implemented.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-10 Thread Hrvoje Niksic
Antoon Pardon antoon.par...@rece.vub.ac.be writes:

 Personaly I don't see a reason to declare in advance that someone
 who wants to treat True differently from non-zero numbers or
 non-empty sequences and does so by a test like:

   if var == Trueorif var is True

 to have written incorrect code.

I wouldn't call it a priori incorrect, but breaking well-established
idioms is like a SHOULD NOT thing in RFC's; you can do that, but you'd
better have a really good reason.

In the case of the gtk code OP quoted, I highly doubt that the author
wanted to special-case True in the way you describe.  It is much more
likely that he made a mistake which happened to work because he never
tested the code with a true value that evalues != 1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-10 Thread NevilleDNZ
On Oct 10, 6:02 pm, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 As for DICT, I think table lookups were still a sufficiently novel concept
 for people to disagree on how they should best be implemented.

I then stumbled over this paper:
Title: List processing in Algol 68 - V. J. Rayward-Smith
International Journal of Mathematical Education in Science and
Technology, 1464-5211, Volume 17, Issue 2, 1986, Pages 239 – 245
* http://www.informaworld.com/index/746867626.pdf - PayWall $30.00
 Abstract
 An Algol 68 implementation of a LISP-like list processing package
 is described. Emphasis is placed upon the importance of Algol 68
 as a teaching tool and upon the need for proving the correctness
 of the programs.

Not having LIST and DICT as part of the base language would make sense
if user contributions were encouraged.  After all that would make way
for evolving the base/primitive language by selecting the most
successful contributions.  IMHO this is where python modules have been
a big success story as it helps time proof the language by allowing
the language to embrace new technologies as they establish themselves
in the market place.

c.f. Anti Gravity: http://xkcd.com/353/

Enjoy
NevilleDNZ
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-10 Thread Lawrence D'Oliveiro
In message
e8a79f5b-a16b-4b33-a116-93cbd07a7...@u5g2000prn.googlegroups.com, 
NevilleDNZ wrote:

 Not having LIST and DICT as part of the base language would make sense
 if user contributions were encouraged.

Unfortunately, they neglected to include any kind of module/package system 
to make this kind of thing easy to do.

But then again, the state of the art in this respect at that time was 
FORTRAN, with its independent, not separate compilation. That meant there 
was no ability to check that the types, or even numbers, of arguments were 
consistent between the definition of a subprogram and a call to it.

This misfeature even carried over to C. C++ tried to finesse it by using 
name-mangling so you got some kind of error from the linker if arguments 
didn’t match, even if you couldn’t actually understand that’s what the error 
meant.

Languages that insisted on being able to do proper compiler-level cross 
checks between separately-compiled modules (e.g. Modula-2, Ada) never really 
became that popular. This saddened me.

 IMHO this is where python modules have been a big success story as it
 helps time proof the language by allowing the language to embrace new
 technologies as they establish themselves in the market place.

Nowadays we take it for granted that the core language should be a strong 
and compact basis to build on, rather than providing lots of built-in 
features, and all the rest should come from run-time libraries.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-09 Thread Lawrence D'Oliveiro
In message i8o1ij$ro...@news.eternal-september.org, BartC wrote:

 NevilleDNZ neville...@gmail.com wrote in message
 news:ad9841df-49a1-4c1b-95d0-e76b72df6...@w9g2000prc.googlegroups.com...

 In Algol68 this would be:
 x:=(i|One,Two,Three|None Of The Above)
 
 The point is, the construction works well when the syntax fully supports
 it.

But note that Algol 68 doesn’t support explicit labels on the alternatives 
in a case expression or statement. That idea came later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-09 Thread NevilleDNZ
On Oct 9, 6:55 pm, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 In message i8o1ij$ro...@news.eternal-september.org, BartC wrote:

  NevilleDNZ neville...@gmail.com wrote in message
 news:ad9841df-49a1-4c1b-95d0-e76b72df6...@w9g2000prc.googlegroups.com...

  In Algol68 this would be:
  x:=(i|One,Two,Three|None Of The Above)

  The point is, the construction works well when the syntax fully supports
  it.

 But note that Algol68 doesn’t support explicit labels on the alternatives
 in a case expression or statement. That idea came later.

Good point... I do ponder why (given that linked lists can easily be
created in Algol68) useful types like LIST and DICT were left out of
the standard prelude.  I do not recall any conversation about this in
the ALGOL Bulletins /* I can reasonably guess why C elected to
excluded these types */

The nearest to explicit labels in Algol68 would be:
STRING x:=(i=0|Zero |:i=1|One |:i=2|Two |:i=3|Three |None Of
The Above);

Basically a compound IF statement... effectively a read only, compile-
time dictionary.

N


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


Re: if the else short form

2010-10-08 Thread NevilleDNZ
On Oct 7, 9:23 am, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)

More like:
x = {1:lambda:One, 2:lambda:Two, 3:lambda:Three}.get(i,
lambda:None Of The Above)()

i.e. deferred evaluation of selected case.

In Algol68 this would be:
x:=(i|One,Two,Three|None Of The Above)

N
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-08 Thread NevilleDNZ
On Oct 7, 10:36 am, BartC b...@freeuk.com wrote:
 i=16
 x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above)
 print x

 Other than efficiency concerns, sometimes you don't want the extra
 side-effects.

 Probably there are workarounds here too, but I suspect the syntax won't be
 quite as pert as the Algol68-style example:

 x = (i | Zero, One, Two | None of the above)  # 0-based

/* ¢ Algol68 case clause is 1-based. ¢ */

However Algol68's CASE ~ IN ~,~,~,~ OUT ~ ESAC clause does mean that
the case items of the clause are not evaluated unless selected.  Here
are some comparisons with python:

$ cat py_case.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This procedure evaluates all the months lengths _before_ building
the dict.
# In that case of month length, they are constants.

def days_in_month0(year, month):
  return {1:31,
2:{True:29,False:28}[year%4==0 and year%100!=0 or year%400==0],
3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31
  }.get(month,None)

# This procedure is closer - in behaviour - to that of the algol68
case clause.
# Keypoint being that individual month length code is not evaluated
unless called()
def days_in_month(year, month):
  return {1:lambda:31,
2:lambda:{True:lambda:29,False:lambda:28}[year%4==0 and year%100!
=0 or year%400==0](),
3:lambda:31,4:lambda:30,5:lambda:31,6:lambda:30,7:lambda:
31,8:lambda:31,9:lambda:30,10:lambda:31,11:lambda:30,12:lambda:31
  }.get(month,None of the above)()

for year in 1899,1900,1901,1999,2000,2001:
  print %4d=%2d%(year,days_in_month0(year, 2)),



Compare with Algol 68:

Brief choice clause example:

PROC days in month = (INT year, month)UNION(INT,STRING):
  (month|31,
(year%×4=0 ∧ year%×100≠0 ∨ year%×400=0|29|28),
31,30,31,30,31,31,30,31,30,31
  |None of the above # or EMPTY #
  );

BOLD choice clause example:

PROC days in month = (INT year, month)UNION(INT,STRING):
  CASE month IN 31,
IF year MOD 4 EQ 0 AND year MOD 100 NE 0 OR year MOD 400 EQ 0 THEN
29 ELSE 28 FI,
31,30,31,30,31,31,30,31,30,31
  OUT None of the above # or EMPTY #
  ESAC;

[]INT years = (1899,1900,1901,1999,2000,2001);
FOR key TO UPB years DO INT year=years[key];
  printf(($4d,=2d $, year, days in month(year, 2)))
OD


$ python py_case.py
1899=28 1900=28 1901=28 1999=28 2000=29 2001=28

There are also the compound IF and CASE conditional clauses:

 IF condition1 THEN statements ELIF condition2 THEN statements [ ELSE
statements ] FI
 brief form if IF clause:  ( condition1 | statements |: condition2 |
statements | statements )

 CASE switch1 IN statements, statements,... OUSE switch2 IN
statements, statements,... [ OUT statements ] ESAC
 brief form of CASE statement:  ( switch1 |
statements,statements,... |: switch2 | statements,statements,... |
statements )

Enjoy
NevilleDNZ
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-08 Thread BartC



NevilleDNZ neville...@gmail.com wrote in message
news:ad9841df-49a1-4c1b-95d0-e76b72df6...@w9g2000prc.googlegroups.com...

On Oct 7, 9:23 am, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:

x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)


More like:
x = {1:lambda:One, 2:lambda:Two, 3:lambda:Three}.get(i,
lambda:None Of The Above)()

i.e. deferred evaluation of selected case.

In Algol68 this would be:
x:=(i|One,Two,Three|None Of The Above)


The point is, the construction works well when the syntax fully supports it.

When it needs the extra clutter that Python demands, it might not be so
worthwhile. Especially as it's not clear whether, even with lambdas, an
entire dictionary needs to be constructed before a selection can be made. In
fact a brief test showed an list+if (or is it tuple? I can never remember)
construction was much faster and much cleaner:

x = (One,Two,Three)[i-1] if 1=i=3 else Other

NevilleDNZ neville...@gmail.com wrote:

BartC b...@freeuk.com wrote:



Probably there are workarounds here too, but I suspect the syntax won't
be
quite as pert as the Algol68-style example:

x = (i | Zero, One, Two | None of the above)  # 0-based


/* ¢ Algol68 case clause is 1-based. ¢ */


Yes, but my example was in Algol68-*style*: 0-based pseudo-syntax just in
case the Pythonians here couldn't get their heads around 1-based indexing..

(I've borrowed a lot from Algol68 when I've needed to design language syntax 
(naturally, just the best bits), and I do normally use 1-based.)


--
Bartc 


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


Re: if the else short form

2010-10-07 Thread BartC

On Thu, 07 Oct 2010 01:36:33 +0100, BartC wrote:



However,  as I mentioned, one problem here is having to evaluate all the
items in the list before selecting one:

...

x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above)


Mel mwil...@the-wire.com wrote in message
news:i8j56e$ub...@speranza.aioe.org...

x = {1: fna, 2: fnb, 3: fnc}.get(i, lambda: None Of The Above) ()


Steven D'Aprano steve-remove-t...@cybersource.com.au wrote in message
news:4cad1817$0$29996$c3e8da3$54964...@news.astraweb.com...

x = {1 : fna, 2 : fnb, 3 : fnc}.get(i, None Of The Above)()


Well, these both kind of work (although the lambda thing is needed in the
second version, when i is out of range).

But you're both taking my example too literally; it was just my way of
testing whether or not each item was in fact evaluated.

In general, each item can be any arbitrary expression, which may or may not
include function calls.

To make this work as expected, I think 'lambda' is needed in front of every
expression, with the expressions written normally (so fn() instead of fn).

But with the syntax becoming more cumbersome, unintuitive, and with unknown
overheads to set up the lambda expressions (is it still necessary to
construct all dictionary entries?), it might be better to just use ordinary
conditional statements.

--
Bartc 


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


Re: if the else short form

2010-10-06 Thread Antoon Pardon
On Wed, Oct 06, 2010 at 01:45:51PM +1300, Lawrence D'Oliveiro wrote:
 In message mailman.1339.1286268545.29448.python-l...@python.org, Antoon 
 Pardon wrote:
 
  On Tue, Oct 05, 2010 at 06:55:33PM +1300, Lawrence D'Oliveiro wrote:
 
  In message mailman.1232.1285927634.29448.python-l...@python.org, Antoon
  Pardon wrote:
  
   On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
  
   BTW adding ==True to a boolean value is redundant and can even break
   for logically true values that don't compare equal to True (such as
   the number 10 or the string foo).
   
   But leaving it out can also break things.
  
  Only in code which was incorrectly written to begin with.
  
  Well you can always define such code as incorrectly written of course.
 
 In this situation, I mean by ???incorrectly written??? code which uses non-
 Boolean values as conditional expressions.

Please be more specific:

A lot of times someone comes with code like the following:

  if len(lst) != 0:
...


and than gets the advise to write it as follows:

  if lst:
...

Do you mean that this second piece of code is incorrectly written,
since it uses a non-boolean value as conditional expression?

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


Re: if the else short form

2010-10-06 Thread Lawrence D'Oliveiro
In message mailman.1384.1286348190.29448.python-l...@python.org, Antoon 
Pardon wrote:

 A lot of times someone comes with code like the following:
 
   if len(lst) != 0:
 ...
 
 
 and than gets the advise to write it as follows:
 
   if lst:
 ...
 
 Do you mean that this second piece of code is incorrectly written ...

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


Re: if the else short form

2010-10-06 Thread James Harris
On 5 Oct, 06:52, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 In message
 e8b46ea8-8d1e-4db9-91ba-501fd1a44...@g18g2000yqk.googlegroups.com, James

 Harris wrote:
  On 29 Sep, 18:20, Seebs usenet-nos...@seebs.net wrote:

  On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:

  button = gtk.Button((False,, True,)[fill==True])

  Oh, what a nasty idiom.

  I'm surprised you don't like this construct. I hadn't seen it until I
  read the OP's question just now. However, it's meaning was immediately
  apparent.

 I’ve used it a lot, from habit because I only started heavily using Python
 with version 2.4.

 I’m still not sure I’m comfortable with “true-part if cond else false-
 part”, when just about every other language manages to standardize on
 “cond ? true-part : false-part”.

For the bit you are not comfortable with do you mean

  (false-part, true-part)[cond]

Of course, this is just an expression containing a selection.
Arbitrarily complex tests can be dealt with in languages where if
statements and case statements can be expressions. IIRC the great
Algol 60 allowed if statements to return a value. I can't say I can
see why a number of subsequent languages don't allow this.

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


Re: if the else short form

2010-10-06 Thread Antoon Pardon
On Wed, Oct 06, 2010 at 09:31:48PM +1300, Lawrence D'Oliveiro wrote:
 In message mailman.1384.1286348190.29448.python-l...@python.org, Antoon 
 Pardon wrote:
 
  A lot of times someone comes with code like the following:
  
if len(lst) != 0:
  ...
  
  
  and than gets the advise to write it as follows:
  
if lst:
  ...
  
  Do you mean that this second piece of code is incorrectly written ...
 
 Yes.

OK, but you do realise this is a minority opinion within the python
community?

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


Re: if the else short form

2010-10-06 Thread BartC
James Harris james.harri...@googlemail.com wrote in message 
news:e8b46ea8-8d1e-4db9-91ba-501fd1a44...@g18g2000yqk.googlegroups.com...

On 29 Sep, 18:20, Seebs usenet-nos...@seebs.net wrote:

On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:

 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

 i have googled for this form but i haven't found nothing, so can any of
 you pass me any reference/link to this particular if/then/else form?

Oh, what a nasty idiom.

Here's the gimmick.
(False,, True,)
is a tuple.  That means you can index it.  For instance:
(False,, True,)[0]
is the string False,.

So, what is the numeric value of fill == True?  Apparently, at least
at the time this was written, it was 0 if fill was not equal to True,
and 1 if fill was equal to True.

Let me say, though, that I'm a C programmer, so I'm coming from a 
language

where the result of 0-or-1 for test operators is guaranteed, and I still
wouldn't use this in live code.  It's insufficiently legible.


I'm surprised you don't like this construct. I hadn't seen it until I
read the OP's question just now. However, it's meaning was immediately
apparent.

I should say where I'm coming from. Contrast the following C and
Python:

 text = fill == true ? True, : False,;   (C)
 text = (False,, True,)[fill == true](Python)


Surely the C should be:  fill ? True, : False,;   ?


I never liked C's ?: construct partly because it doesn't scale well.
To accept more than two options it requires the programmer to build a
small hierarchy which can be awful to read and may be best expressed
as a separate function. I'd rather have a language change a predicate
to a small integer and use that to index a set of results - and this
is exactly what the OP's tutorial does.


I use this syntax where there are two possibilities chosen according to 
condition 'a':


(a | b | c)

similar to C's ?: operator. Where there are N possibilities chosen from a 
linear set, I use:


(i | a, b, c, ... |z)  # indexed from 1, default to z

(I think from Algol68 originally.)

The difference from what the Python is doing above, is that only one of the 
possibilities is ever evaluated. Extrapolating the syntax a little, Python I 
think will evaluate all N expressions (maybe even construct the tuple), 
before choosing one.


And I'm not sure there is provision for  a default value either, without 
having a far more complex expression:


x = (One,Two,Three) [i-1]

While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and generates 
an error for the rest (I'm sure Python has myriad ways of achieving this 
succinctly,  but this isn't it...)



As another hypothetical example where sgn() returns -1, 0 or +1

 position = (less, equal, greater)[sgn(a - b) + 1]



Though where the list gets much longer it would be good to be able to
label the cases for legibility.


You can do, until you want to insert an item in the middle and have to 
re-label everything...


For more complex cases I'd just use a conventional case or switch expression 
which (in my syntax at least), also evaluates just one expression, and 
returns that value. But then you can also start using if-else chains, so 
this is no longer a compact construction useful in an expression.


--
Bartc 


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


Re: if the else short form

2010-10-06 Thread Lawrence D'Oliveiro
In message i8i1h8$dc...@news.eternal-september.org, BartC wrote:

 I use this syntax where there are two possibilities chosen according to
 condition 'a':
 
 (a | b | c)

Algol 68!

 x = (One,Two,Three) [i-1]
 
 While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and generates
 an error for the rest ...

x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-06 Thread BartC



Lawrence D'Oliveiro l...@geek-central.gen.new_zealand wrote in message 
news:i8j0dg$lh...@lust.ihug.co.nz...

In message i8i1h8$dc...@news.eternal-september.org, BartC wrote:



x = (One,Two,Three) [i-1]

While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and 
generates

an error for the rest ...


x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)


Yes, I expected Python to come up with something (it always does).

However,  as I mentioned, one problem here is having to evaluate all the 
items in the list before selecting one:


def fna():
   print FNA CALLED
   return One
def fnb():
   print FNB CALLED
   return Two
def fnc():
   print FNC CALLED
   return Three

i=16
x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above)
print x

Other than efficiency concerns, sometimes you don't want the extra 
side-effects.


Probably there are workarounds here too, but I suspect the syntax won't be 
quite as pert as the Algol68-style example:


x = (i | Zero, One, Two | None of the above)  # 0-based

--
bartc 
--

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


Re: if the else short form

2010-10-06 Thread Mel
BartC wrote:

 
 
 Lawrence D'Oliveiro l...@geek-central.gen.new_zealand wrote in message
 news:i8j0dg$lh...@lust.ihug.co.nz...
 In message i8i1h8$dc...@news.eternal-september.org, BartC wrote:
 
 x = (One,Two,Three) [i-1]

 While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and
 generates
 an error for the rest ...

 x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)
 
 Yes, I expected Python to come up with something (it always does).
 
 However,  as I mentioned, one problem here is having to evaluate all the
 items in the list before selecting one:
 
 def fna():
 print FNA CALLED
 return One
 def fnb():
 print FNB CALLED
 return Two
 def fnc():
 print FNC CALLED
 return Three
 
 i=16
 x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above)
 print x
 
 Other than efficiency concerns, sometimes you don't want the extra
 side-effects.
 
 Probably there are workarounds here too,

The workaround would be (untested)
x = {1: fna, 2: fnb, 3: fnc}.get(i, lambda: None Of The Above) ()

Mel.

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


Re: if the else short form

2010-10-06 Thread Steven D'Aprano
On Thu, 07 Oct 2010 01:36:33 +0100, BartC wrote:


 However,  as I mentioned, one problem here is having to evaluate all the
 items in the list before selecting one:
 
 def fna():
 print FNA CALLED
 return One
 def fnb():
 print FNB CALLED
 return Two
 def fnc():
 print FNC CALLED
 return Three
 
 i=16
 x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above) 
 print x
 
 Other than efficiency concerns, sometimes you don't want the extra
 side-effects.

Try this instead:

i=16
x = {1 : fna, 2 : fnb, 3 : fnc}.get(i, None Of The Above)()
print x


Also known as the command dispatch pattern.


First class functions are a wonderful thing-ly y'rs, 


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


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message 
e8b46ea8-8d1e-4db9-91ba-501fd1a44...@g18g2000yqk.googlegroups.com, James 
Harris wrote:

 On 29 Sep, 18:20, Seebs usenet-nos...@seebs.net wrote:

 On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:

 button = gtk.Button((False,, True,)[fill==True])

 Oh, what a nasty idiom.
 
 I'm surprised you don't like this construct. I hadn't seen it until I
 read the OP's question just now. However, it's meaning was immediately
 apparent.

I’ve used it a lot, from habit because I only started heavily using Python 
with version 2.4.

I’m still not sure I’m comfortable with “true-part if cond else false-
part”, when just about every other language manages to standardize on 
“cond ? true-part : false-part”.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message mailman.1166.1285774349.29448.python-l...@python.org, Philip 
Semanchuk wrote:

 Does Python make any guarantee that int(True) == 1 and int(False) == 0
 will always hold, or are their values an implementation detail?

There has never been a rationally-designed language where this was merely 
“an implementation detail”.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message 877hi44w53@xemacs.org, Hrvoje Niksic wrote:

 BTW adding ==True to a boolean value is redundant and can even break
 for logically true values that don't compare equal to True (such as the
 number 10 or the string foo).

I wonder if there’s a name for this sort of thing: “boolnoob”, perhaps. Or 
“UUOBC” (“Useless Use Of Boolean Comparison”).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message mailman.1232.1285927634.29448.python-l...@python.org, Antoon 
Pardon wrote:

 On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:

 BTW adding ==True to a boolean value is redundant and can even break
 for logically true values that don't compare equal to True (such as the
 number 10 or the string foo).
 
 But leaving it out can also break things.

Only in code which was incorrectly written to begin with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message 4ca96440$0$1674$742ec...@news.sonic.net, John Nagle wrote:

  Yes, bool is a subtype of int in Python.  This was
 because the original design of Python didn't have bool
 (a rather strange mistake for a language designed this late)
 and the retrofit had to have some backwards compatibility.

What’s the alternative? Java’s definition of “bool” is crap.

The Pascal/Ada approach was to introduce the general concept of “enumerated 
types”, which were a subclass of “discrete types” (including integers and 
subranges thereof). Boolean was just a built-in enumerated type.

What’s a language like Python, which has no enumerated types, to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Antoon Pardon
On Tue, Oct 05, 2010 at 06:55:33PM +1300, Lawrence D'Oliveiro wrote:
 In message mailman.1232.1285927634.29448.python-l...@python.org, Antoon 
 Pardon wrote:
 
  On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
 
  BTW adding ==True to a boolean value is redundant and can even break
  for logically true values that don't compare equal to True (such as the
  number 10 or the string foo).
  
  But leaving it out can also break things.
 
 Only in code which was incorrectly written to begin with.

Well you can always define such code as incorrectly written of course.

I find it odd that on the one hand, if static types get mentioned, the
python people in general are against it because they like the freedom
that a variable can be bound to objects of different types.

But then when they see code, that explicitly checks for True and
thus might make use of that possibility and as such behave differently
in case of True or non-zero number values, the reaction is to
consider that incorrectly written code by definition.

Personaly I don't see a reason to declare in advance that someone
who wants to treat True differently from non-zero numbers or
non-empty sequences and does so by a test like:

  if var == Trueorif var is True

to have written incorrect code.


The designers have chosen that a lot of different results act
as true in a boolean context. A programmer trying to solve
a particular problem doesn't necessary want to treat als
those possible results the same. So if the programmer wants
to treat True differently from those other true-results I
don't see an other option than using a test like above.

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


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message mailman.1339.1286268545.29448.python-l...@python.org, Antoon 
Pardon wrote:

 On Tue, Oct 05, 2010 at 06:55:33PM +1300, Lawrence D'Oliveiro wrote:

 In message mailman.1232.1285927634.29448.python-l...@python.org, Antoon
 Pardon wrote:
 
  On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
 
  BTW adding ==True to a boolean value is redundant and can even break
  for logically true values that don't compare equal to True (such as
  the number 10 or the string foo).
  
  But leaving it out can also break things.
 
 Only in code which was incorrectly written to begin with.
 
 Well you can always define such code as incorrectly written of course.

In this situation, I mean by “incorrectly written” code which uses non-
Boolean values as conditional expressions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-05 Thread Andreas Waldenburger
On Tue, 05 Oct 2010 18:54:42 +1300 Lawrence D'Oliveiro
l...@geek-central.gen.new_zealand wrote:

 “boolnoob”

Bwahahahah! Nice!

I'd love to say that I'll add this to my active vocabulary, but I don't
think there will be enough opportunities to use it. :-/

/W

-- 
INVALID? DE!

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


Re: if the else short form

2010-10-05 Thread Lawrence D'Oliveiro
In message 20101005223520.3f5d9...@geekmail.invalid, Andreas Waldenburger 
wrote:

 On Tue, 05 Oct 2010 18:54:42 +1300 Lawrence D'Oliveiro
 l...@geek-central.gen.new_zealand wrote:
 
 “boolnoob”
 
 Bwahahahah! Nice!

And of course, an instance of such boolnoobery can be referred to as a 
boolnoobism.

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


Re: if the else short form

2010-10-04 Thread John Nagle

On 10/1/2010 10:19 PM, Paul Rubin wrote:

Steven D'Apranost...@remove-this-cybersource.com.au  writes:

Incorrect. bools *are* ints in Python, beyond any doubt.


 Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58)
   type(3)==type(True)
 False


Yes, bool is a subtype of int in Python.  This was
because the original design of Python didn't have bool
(a rather strange mistake for a language designed this late)
and the retrofit had to have some backwards compatibility.

That's why lame results such as True + True being 2.

John Nagle

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


Re: if the else short form

2010-10-04 Thread James Harris
On 29 Sep, 18:20, Seebs usenet-nos...@seebs.net wrote:
 On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:

  Hi all,
  I'm studying PyGTK tutorial and i've found this strange form:

  button = gtk.Button((False,, True,)[fill==True])

  the label of button is True if fill==True, is False otherwise.

  i have googled for this form but i haven't found nothing, so can any of
  you pass me any reference/link to this particular if/then/else form?

 Oh, what a nasty idiom.

 Here's the gimmick.
         (False,, True,)
 is a tuple.  That means you can index it.  For instance:
         (False,, True,)[0]
 is the string False,.

 So, what is the numeric value of fill == True?  Apparently, at least
 at the time this was written, it was 0 if fill was not equal to True,
 and 1 if fill was equal to True.

 Let me say, though, that I'm a C programmer, so I'm coming from a language
 where the result of 0-or-1 for test operators is guaranteed, and I still
 wouldn't use this in live code.  It's insufficiently legible.

I'm surprised you don't like this construct. I hadn't seen it until I
read the OP's question just now. However, it's meaning was immediately
apparent.

I should say where I'm coming from. Contrast the following C and
Python:

  text = fill == true ? True, : False,;   (C)
  text = (False,, True,)[fill == true](Python)

I never liked C's ?: construct partly because it doesn't scale well.
To accept more than two options it requires the programmer to build a
small hierarchy which can be awful to read and may be best expressed
as a separate function. I'd rather have a language change a predicate
to a small integer and use that to index a set of results - and this
is exactly what the OP's tutorial does.

I'm not saying you are wrong, merely expressing a different view and
explaining why.

As another hypothetical example where sgn() returns -1, 0 or +1

  position = (less, equal, greater)[sgn(a - b) + 1]

Though where the list gets much longer it would be good to be able to
label the cases for legibility.

cc. comp.lang.misc

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


Re: if the else short form

2010-10-03 Thread Andreas Waldenburger
On Fri, 1 Oct 2010 00:42:34 -0700 (PDT) bruno.desthuilli...@gmail.com
bruno.desthuilli...@gmail.com wrote:

 On 30 sep, 19:22, Andreas Waldenburger use...@geekmail.invalid
 wrote:
  On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)
 
  bruno.desthuilli...@gmail.com bruno.desthuilli...@gmail.com
  wrote:
   On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote:
On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:
 button = gtk.Button((False,, True,)[fill==True])
 
Oh, what a nasty idiom.
 
   Well, it's not very different from dict-based dispatch , which is
   the core of OO polymorphic dispatch in quite a few dynamic OOPLs.
 
   Anyway, it's a common Python idiom and one that's not specially
   hard to grasp so I don't see any legibility problem here.
 
  But it does violate the explicit is better than implicit tenet,
  don't you think?
 
 Why so ? The doc clearly states that booleans are integers with True
 == 1 and False == 0, so there's nothing implicit here.
 
The Perl docs state a lot of things about Perl also; that doesn't make
Perl any more explicit as a language.

I understand the term explicit to mean (broadly) code that
documents itself as clearly as possible. To me the
[A,B][bool(switch)] idiom doesn't readily translate into an English
phrase, even though I understand it. As such, it takes me longer to
grasp it's purpose than an .. if .. else ... expression. Therefore, I
consider this functionality implicit, rather than explicit.

This may be a too liberal a reading of said tenet, so ... yeah.

/W

-- 
INVALID? DE!

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


Re: if the else short form

2010-10-02 Thread Steven D'Aprano
On Fri, 01 Oct 2010 22:19:14 -0700, Paul Rubin wrote:

 Steven D'Aprano st...@remove-this-cybersource.com.au writes:
 Incorrect. bools *are* ints in Python, beyond any doubt.
 
 Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58)
  type(3)==type(True)
 False

So? Instances of a subclasses are still instances of the superclass.

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


Re: if the else short form

2010-10-02 Thread Arnaud Delobelle
Paul Rubin no.em...@nospam.invalid writes:

 Steven D'Aprano st...@remove-this-cybersource.com.au writes:
 Incorrect. bools *are* ints in Python, beyond any doubt.

 Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58) 
  type(3)==type(True)
 False

Of course, but it's the wrong thing to ask if you want know if bools are
ints.  To find out via their types, you should ask:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
 issubclass(type(True), type(3))
True

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


Re: if the else short form

2010-10-02 Thread Ian
On Oct 1, 11:19 pm, Paul Rubin no.em...@nospam.invalid wrote:
 Steven D'Aprano st...@remove-this-cybersource.com.au writes:
  Incorrect. bools *are* ints in Python, beyond any doubt.

     Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58)
      type(3)==type(True)
     False

 -1  False  True  2
True

 True + True
2

 hex(True)
'0x1'

 True.real, True.imag
(1, 0)

If it looks like a duck, swims like a duck, and quacks like a duck...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-01 Thread bruno.desthuilli...@gmail.com
On 30 sep, 19:22, Andreas Waldenburger use...@geekmail.invalid
wrote:
 On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)

 bruno.desthuilli...@gmail.com bruno.desthuilli...@gmail.com wrote:
  On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote:
   On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:
button = gtk.Button((False,, True,)[fill==True])

   Oh, what a nasty idiom.

  Well, it's not very different from dict-based dispatch , which is the
  core of OO polymorphic dispatch in quite a few dynamic OOPLs.

  Anyway, it's a common Python idiom and one that's not specially hard
  to grasp so I don't see any legibility problem here.

 But it does violate the explicit is better than implicit tenet, don't
 you think?

Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.

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


Re: if the else short form

2010-10-01 Thread Antoon Pardon
On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
 Tracubik affdfsdfds...@b.com writes:
 
  Hi all,
  I'm studying PyGTK tutorial and i've found this strange form:
 
  button = gtk.Button((False,, True,)[fill==True])
 
  the label of button is True if fill==True, is False otherwise.
 
 The tutorial likely predates if/else expression syntax introduced in
 2.5, which would be spelled as:
 
 button = gtk.Button(True if fill else False)
 
 BTW adding ==True to a boolean value is redundant and can even break
 for logically true values that don't compare equal to True (such as the
 number 10 or the string foo).

But leaving it out can also break things. If for some reason a variable
can have a boolean or a numeric value, that doesn't mean the coder wants
to treat 0 the same as False or any non-zero number the same as True.

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


Re: if the else short form

2010-10-01 Thread Antoon Pardon
On Wed, Sep 29, 2010 at 05:58:16AM -0700, bruno.desthuilli...@gmail.com wrote:
 On 29 sep, 13:38, Hrvoje Niksic hnik...@xemacs.org wrote:
  Tracubik affdfsdfds...@b.com writes:
 
   button = gtk.Button((False,, True,)[fill==True])
 
 (snip)
 
  BTW adding ==True to a boolean value is redundant and can even break
  for logically true values that don't compare equal to True (such as the
  number 10 or the string foo).
 
 Note that if fill is actually an int outside the (0, 1) domain, it
 will break too. The correct test would be:
 
  (False,, True,)[bool(fill)])

That is assuming the original coder would want the argument True,
in such cases. You don't know that.

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


Re: if the else short form

2010-10-01 Thread John Nagle

On 10/1/2010 12:42 AM, bruno.desthuilli...@gmail.com wrote:

On 30 sep, 19:22, Andreas Waldenburgeruse...@geekmail.invalid
wrote:

On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)

bruno.desthuilli...@gmail.combruno.desthuilli...@gmail.com  wrote:

On 29 sep, 19:20, Seebsusenet-nos...@seebs.net  wrote:

On 2010-09-29, Tracubikaffdfsdfds...@b.com  wrote:

button = gtk.Button((False,, True,)[fill==True])



Oh, what a nasty idiom.



Well, it's not very different from dict-based dispatch , which is the
core of OO polymorphic dispatch in quite a few dynamic OOPLs.



Anyway, it's a common Python idiom and one that's not specially hard
to grasp so I don't see any legibility problem here.


But it does violate the explicit is better than implicit tenet, don't
you think?


Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.


Python bool values are NOT integers.  They can be coerced to
integers for historical reasons.  But str(True) is True.

The above could be better written as

button = gtk.Button(str(fill))

John Nagle

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


Re: if the else short form

2010-10-01 Thread Ethan Furman

John Nagle wrote:

On 10/1/2010 12:42 AM, bruno.desthuilli...@gmail.com wrote:

On 30 sep, 19:22, Andreas Waldenburgeruse...@geekmail.invalid
wrote:



But it does violate the explicit is better than implicit tenet, don't
you think?


Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.


Python bool values are NOT integers.  They can be coerced to
integers for historical reasons.  But str(True) is True.


Okay, so they are *subtypes* of integers, to be precise... but what, 
exactly, does the string representation of an object have to do with its 
type?


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


Re: if the else short form

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 11:23:25 -0700, John Nagle wrote:

 Why so ? The doc clearly states that booleans are integers with True ==
 1 and False == 0, so there's nothing implicit here.
 
  Python bool values are NOT integers.  They can be coerced to
 integers for historical reasons.  

Incorrect. bools *are* ints in Python, beyond any doubt.

 isinstance(True, int)
True

True and False are instances of int. That's all you need to know.


 But str(True) is True.

I assume that you're not comparing the literal strings str(True) and 
True (which would make your claim incorrect). Nevertheless, leaving out 
the quotes is also incorrect:

 str(True) is True
False

The only way to get your claim to work is to mix'n'match quotation marks, 
leaving one pair in and dropping the other:

 str(True) is True
True

But so what? What do you think that proves? All it shows is an 
implementation detail to do with caching of certain small strings:

 str(5) is 5
True



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


Re: if the else short form

2010-10-01 Thread Paul Rubin
Steven D'Aprano st...@remove-this-cybersource.com.au writes:
 Incorrect. bools *are* ints in Python, beyond any doubt.

Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58) 
 type(3)==type(True)
False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-09-30 Thread Sion Arrowsmith
Andreas Waldenburger  use...@geekmail.invalid wrote:
http://docs.python.org/release/3.1/reference/datamodel.html#the-standard-type-hierarchy
[ ... ]
Boolean values behave like the values 0 and 1, respectively, in
almost all contexts, the exception being that when converted to a
string, the strings False or True are returned, respectively.

Hmm. So the original problem of:

button = gtk.Button((False,, True,)[fill==True])

could also rewritten as:

button = gtk.Button(str(bool(fill))+,)

-- 
\S

   under construction

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


Re: if the else short form

2010-09-30 Thread bruno.desthuilli...@gmail.com
On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote:
 On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:
  button = gtk.Button((False,, True,)[fill==True])

 Oh, what a nasty idiom.


Well, it's not very different from dict-based dispatch , which is the
core of OO polymorphic dispatch in quite a few dynamic OOPLs.

Anyway, it's a common Python idiom and one that's not specially hard
to grasp so I don't see any legibility problem here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-09-30 Thread Emile van Sebille

On 9/30/2010 3:21 AM Sion Arrowsmith said...

Andreas Waldenburgeruse...@geekmail.invalid  wrote:

http://docs.python.org/release/3.1/reference/datamodel.html#the-standard-type-hierarchy
[ ... ]
Boolean values behave like the values 0 and 1, respectively, in
almost all contexts, the exception being that when converted to a
string, the strings False or True are returned, respectively.


Hmm. So the original problem of:

button = gtk.Button((False,, True,)[fill==True])

could also rewritten as:

button = gtk.Button(str(bool(fill))+,)



I think I'd prefer

button = gtk.Button(%s, % bool(fill))

Emile




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


Re: if the else short form

2010-09-30 Thread Andreas Waldenburger
On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)
bruno.desthuilli...@gmail.com bruno.desthuilli...@gmail.com wrote:

 On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote:
  On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:
   button = gtk.Button((False,, True,)[fill==True])
 
  Oh, what a nasty idiom.
 
 
 Well, it's not very different from dict-based dispatch , which is the
 core of OO polymorphic dispatch in quite a few dynamic OOPLs.
 
 Anyway, it's a common Python idiom and one that's not specially hard
 to grasp so I don't see any legibility problem here.

But it does violate the explicit is better than implicit tenet, don't
you think?

/W

-- 
INVALID? DE!

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


if the else short form

2010-09-29 Thread Tracubik
Hi all,
I'm studying PyGTK tutorial and i've found this strange form:

button = gtk.Button((False,, True,)[fill==True])

the label of button is True if fill==True, is False otherwise.

i have googled for this form but i haven't found nothing, so can any of 
you pass me any reference/link to this particular if/then/else form?

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


Re: if the else short form

2010-09-29 Thread Joost Molenaar
Hi Nico, it's converting fill==True to an int, thereby choosing the
string False, or True, by indexing into the tuple.

Try this in an interpreter:
 ['a','b'][False]
'a'
 ['a','b'][True]
'b'
 int(False)
0
 int(True)
1


Joost

On 29 September 2010 12:42, Tracubik affdfsdfds...@b.com wrote:

 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

 i have googled for this form but i haven't found nothing, so can any of
 you pass me any reference/link to this particular if/then/else form?

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


Re: if the else short form

2010-09-29 Thread Tom Potts
This is just a sneaky shorthand, which is fine if that's what you want, but
it makes it harder to read.  The reason it works is that 'fill==True' is a
boolean expression, which evaluates to True or False, but if you force a
True into being an integer, it will be 1, and a False will become 0.  Try
writing 'True == 1' on the Python interpreter to see what I mean.  So this
code snippet is creating a tuple with two elements, and then selecting the
first if 'fill==True' is False, or 0, and selecting the second if
'fill==True' is True, or 1.

As I say, this kind of coding is absolutely fine, but it makes things harder
to read and doesn't really save much space.  I wouldn't recommend using this
kind of style yourself, at least until you're more familiar with programming
in Python.

Tom

On 29 September 2010 11:42, Tracubik affdfsdfds...@b.com wrote:

 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

 i have googled for this form but i haven't found nothing, so can any of
 you pass me any reference/link to this particular if/then/else form?

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

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


Re: if the else short form

2010-09-29 Thread Hrvoje Niksic
Tracubik affdfsdfds...@b.com writes:

 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

The tutorial likely predates if/else expression syntax introduced in
2.5, which would be spelled as:

button = gtk.Button(True if fill else False)

BTW adding ==True to a boolean value is redundant and can even break
for logically true values that don't compare equal to True (such as the
number 10 or the string foo).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-list] if the else short form

2010-09-29 Thread Brendan Simon (eTRIX)
 On 29/09/10 9:20 PM, python-list-requ...@python.org wrote:
 Subject:
 if the else short form
 From:
 Tracubik affdfsdfds...@b.com
 Date:
 29 Sep 2010 10:42:37 GMT

 To:
 python-list@python.org


 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

 i have googled for this form but i haven't found nothing, so can any of 
 you pass me any reference/link to this particular if/then/else form?


As others have pointed out, a tuple with two items is created and then
indexed by the integer conversion of conditional.  It is creative
coding but I wouldn't recommend using it either.

For this particular case you may achieve the same thing with:

button = gtk.Button(str(fill==True))

or possibly just:

button = gtk.Button(fill==True)

It's a little better but still not great.

A verbose form of something more generic may be:

if fill:

label = 'True'

else:

label = 'False'

button = gtk.Button(label)

or possibly:

label = 'True' if fill else 'False'
button = gtk.Button(label)

or using a dict for label lookup:

label = { True : 'True', False : 'False' }
button = gtk.Button(label[fill])


Cheers, Brendan.

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


Re: if the else short form

2010-09-29 Thread bruno.desthuilli...@gmail.com
On 29 sep, 13:38, Hrvoje Niksic hnik...@xemacs.org wrote:
 Tracubik affdfsdfds...@b.com writes:

  button = gtk.Button((False,, True,)[fill==True])

(snip)

 BTW adding ==True to a boolean value is redundant and can even break
 for logically true values that don't compare equal to True (such as the
 number 10 or the string foo).

Note that if fill is actually an int outside the (0, 1) domain, it
will break too. The correct test would be:

 (False,, True,)[bool(fill)])


 ['a', 'b'][bool(10)]
'b'
 ['a', 'b'][bool('')]
'a'
 ['a', 'b'][bool(yes)]
'b'
 ['a', 'b'][bool([])]
'a'
 ['a', 'b'][bool([42, 24])]
'b'
 ['a', 'b'][bool(None)]
'a'

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


Re: if the else short form

2010-09-29 Thread Alex Willmer
On Sep 29, 12:38 pm, Hrvoje Niksic hnik...@xemacs.org wrote:
 Tracubik affdfsdfds...@b.com writes:
  Hi all,
  I'm studying PyGTK tutorial and i've found this strange form:

  button = gtk.Button((False,, True,)[fill==True])

  the label of button is True if fill==True, is False otherwise.

 The tutorial likely predates if/else expression syntax introduced in
 2.5, which would be spelled as:

 button = gtk.Button(True if fill else False)

 BTW adding ==True to a boolean value is redundant and can even break
 for logically true values that don't compare equal to True (such as the
 number 10 or the string foo).

Totally agreed with one nit. If one chooses to fake

x = true_val if expr else false_val

prior to Python 2.5, with

x = (false_val, true_val)[expr]

then one should ensure that expr evaluates to either 0, 1 or a bool.
If expr evaluates to fred or 42 a TypeError or IndexError will
occur. So better to use (in original line)

 button = gtk.Button((False,, True,)[bool(fill)])

but still best for readability, to use a full if-else block
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-09-29 Thread Philip Semanchuk

On Sep 29, 2010, at 7:19 AM, Tom Potts wrote:

 This is just a sneaky shorthand, which is fine if that's what you want, but
 it makes it harder to read.  The reason it works is that 'fill==True' is a
 boolean expression, which evaluates to True or False, but if you force a
 True into being an integer, it will be 1, and a False will become 0.  Try
 writing 'True == 1' on the Python interpreter to see what I mean.  So this
 code snippet is creating a tuple with two elements, and then selecting the
 first if 'fill==True' is False, or 0, and selecting the second if
 'fill==True' is True, or 1.
 
 As I say, this kind of coding is absolutely fine, but it makes things harder
 to read and doesn't really save much space.  I wouldn't recommend using this
 kind of style yourself, at least until you're more familiar with programming
 in Python.

Does Python make any guarantee that int(True) == 1 and int(False) == 0 will 
always hold, or are their values an implementation detail?

Thanks
Philip


 On 29 September 2010 11:42, Tracubik affdfsdfds...@b.com wrote:
 
 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:
 
 button = gtk.Button((False,, True,)[fill==True])
 
 the label of button is True if fill==True, is False otherwise.
 
 i have googled for this form but i haven't found nothing, so can any of
 you pass me any reference/link to this particular if/then/else form?
 
 thanks
 Nico
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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


Re: if the else short form

2010-09-29 Thread Emile van Sebille

On 9/29/2010 5:53 AM Philip Semanchuk said...


Does Python make any guarantee that int(True) == 1 and int(False) == 0 will 
always hold, or are their values an implementation detail?



I had exactly this same question occur to me yesterday, and yes, I 
believe it does.  From 
http://docs.python.org/reference/datamodel.html#objects-values-and-types


Booleans
These represent the truth values False and True. The two objects 
representing the values False and True are the only Boolean objects. The 
Boolean type is a subtype of plain integers, and Boolean values behave 
like the values 0 and 1, respectively, in almost all contexts, the 
exception being that when converted to a string, the strings False or 
True are returned, respectively.


Emile

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


Re: if the else short form

2010-09-29 Thread Andreas Waldenburger
On Wed, 29 Sep 2010 08:53:17 -0400 Philip Semanchuk
phi...@semanchuk.com wrote:

 Does Python make any guarantee that int(True) == 1 and int(False) ==
 0 will always hold, or are their values an implementation detail?
 

http://docs.python.org/release/3.1/reference/datamodel.html#the-standard-type-hierarchy

Booleans (bool)

These represent the truth values False and True. The two objects
representing the values False and True are the only Boolean
objects. The Boolean type is a subtype of the integer type, and
Boolean values behave like the values 0 and 1, respectively, in
almost all contexts, the exception being that when converted to a
string, the strings False or True are returned, respectively.


/W


-- 
INVALID? DE!

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


Re: if the else short form

2010-09-29 Thread Seebs
On 2010-09-29, Tracubik affdfsdfds...@b.com wrote:
 Hi all,
 I'm studying PyGTK tutorial and i've found this strange form:

 button = gtk.Button((False,, True,)[fill==True])

 the label of button is True if fill==True, is False otherwise.

 i have googled for this form but i haven't found nothing, so can any of 
 you pass me any reference/link to this particular if/then/else form?

Oh, what a nasty idiom.

Here's the gimmick.
(False,, True,)
is a tuple.  That means you can index it.  For instance:
(False,, True,)[0]
is the string False,.

So, what is the numeric value of fill == True?  Apparently, at least
at the time this was written, it was 0 if fill was not equal to True,
and 1 if fill was equal to True.

Let me say, though, that I'm a C programmer, so I'm coming from a language
where the result of 0-or-1 for test operators is guaranteed, and I still
wouldn't use this in live code.  It's insufficiently legible.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list