PEP308: Yet another syntax proposal

holger krekel pyth at devel.trillke.net
Mon Feb 10 17:28:11 EST 2003


David Eppstein wrote:
> On 2/10/03 9:02 PM +0100 holger krekel <pyth at devel.trillke.net> wrote:
> >> I posted one several hundred messages back:
> >>    cols[i] if i >= 0 else None
> >>
> >> It's from real code, an example where the and/or trick fails because you
> >> don't know the truth status of cols[i], and an example where the guard
> >> might serve to prevent an array out of bounds exception.
> >
> > ok.  I think i have seen that before but also thought
> > that list/tuple show grow a 'get' method (parallel to
> > the dict.__getitem__ / dict.get pair).
> 
> cols.get(i,None) would do the wrong thing if i==-1 -- I really want None, 
> not the last item in cols, for this case.

ok. 

> > And i thought why would someone really need to do this
> > check?  Either you allow negative indices (which work on
> > list/tuples) or you don't in which case you might like
> > to get into some error-path anyway.  How do you get
> > to 'i<0' anyway?
> 
> It's a flag value to distinguish a "select all" menu item from the menu 
> items referring to individual columns.

i see.  

When i had situations like this I rewrote it to get the special "select all" 
value not interfere with usual list/tuple-index semantics.  E.g. using a 
dummy-class for "select_all" rather than reusing an otherwise valid key index.  

> > This reinforces an earlier thought about PEP-308 alternatives,
> > which might read as follows:
> >
> >     cols[i] except IndexError: None
> 
> Again, not good, i==-1 doesn't cause the IndexError unless cols is empty.

right. with my above "class select_all: pass" this would work nicely, though. 

> What would work in my case (since i<0 always ends up being exactly -1) 
> would be to copy the cols array, append None to the copy, and then use 
> cols[i] without checks.  I happen to think that would be more obscure than 
> the if-then-else code I've been using.

Sure.  But I'd rather have my co-coders think about easier ways rather
having to understand ternary operations often.  Had i seen your above code 

    cols[i] if i >= 0 else None

just on its own i would be puzzled (which i was).  May i ask
you to show the complete function where this came from? 

thanks for your patience (if any is left :-),

    holger





More information about the Python-list mailing list