while expression feature proposal

Dan Loewenherz dloewenherz at gmail.com
Fri Oct 26 11:29:54 EDT 2012


On Thursday, October 25, 2012 11:06:01 PM UTC-7, Paul Rubin wrote:
> Dan Loewenherz <dloewenherz at gmail.com> writes:
> 
> > In this case, profile_id is "None" when the loop breaks. It would be
> 
> > much more straightforward (and more Pythonic, IMO), to write:
> 
> >
> 
> >     client = StrictRedis()
> 
> >     while client.spop("profile_ids") as profile_id:
> 
> >         print profile_id
> 
> 
> 
> That is pretty loose, in my opinion.  If the loop is supposed to return
> 
> a string until breaking on None, the break test should explicitly check
> 
> for None rather than rely on an implicit bool conversion that will also
> 
> test as false on an empty string.  Code that handles strings should do
> 
> the right thing with the empty string.  What you posted relies on an
> 
> unstated assumption that the strings that come back are never empty.
> 

I think this is a good point. However, I can't think of any situation where I'd want to work with an empty string (in the applications I've worked with, at least).

We also don't special case things like this just because x is an empty string. If this "while EXPR as VAR" thing were to move forward, we shouldn't treat the truth testing any differently than how we already do. IMO we should write our applications with the understanding that '' will return False and work with that.

Here's a workaround BTW. Just have that method return a tuple, and do the truth testing yourself if you feel it's necessary.

    while client.spop("profile_ids") as truthy, profile_id:
        if not truthy:
            break

        print profile_id

Here, client.spop returns a tuple, which will always returns true. We then extract the first element and run a truth test on it. The function we use is in charge of determining the truthiness.

Dan



More information about the Python-list mailing list