Connecting Tech Pros Worldwide Forums | Help | Site Map

Re: first of not None

Serge Matveenko
Guest
 
Posts: n/a
#1: Oct 9 '08
On 10/9/08, Serge Matveenko <serge@matveenko.ruwrote:
Quote:
I need to put in the var property of the first object from the list
that is not None. Somth like:
>
foo = first_of([any, beny, riki,]).name
>
Dont want to ugly if-cascade:
>
foo = any.name if name is not None else beny.name if beny is not None \
else riki.name if riki is not None
after some play with interpreter and Python logic i've got this:

objs = [None, 'dfgh', None,]
obj_l = [obj.__len__() for obj in objs if obj is not None][0]

Now the question is this is lazy or not? And how could i make it lazy?


--
Serge Matveenko
mailto:serge@matveenko.ru
http://serge.matveenko.ru/

Diez B. Roggisch
Guest
 
Posts: n/a
#2: Oct 9 '08

re: Re: first of not None


Serge Matveenko schrieb:
Quote:
On 10/9/08, Serge Matveenko <serge@matveenko.ruwrote:
Quote:
>I need to put in the var property of the first object from the list
>that is not None. Somth like:
>>
>foo = first_of([any, beny, riki,]).name
>>
>Dont want to ugly if-cascade:
>>
>foo = any.name if name is not None else beny.name if beny is not None \
>else riki.name if riki is not None
>
after some play with interpreter and Python logic i've got this:
>
objs = [None, 'dfgh', None,]
obj_l = [obj.__len__() for obj in objs if obj is not None][0]

The usual way to compute the len is to use

len(obj)

Quote:
Now the question is this is lazy or not? And how could i make it lazy?
No, it's not. You could make it a generator expression:


obj_l = (len(obj) for obj in objs if obj is not None).next()

Diez
Closed Thread