Generating a list of None

Bengt Richter bokr at oz.net
Sat Jul 16 16:48:09 EDT 2005


On 16 Jul 2005 02:31:28 -0700, "Raymond Hettinger" <python at rcn.com> wrote:

>[Bengt Richter]
>> how about (untested)
>>
>>  def get_options(opts):
>>      """Return True or False if an option is set or not"""
>>      return [1 for val in vars(opts).values() if val is not None] and True or False
>
>While we're tossing around hacks and coding atrocities, we should note
>that:
>
>   not not x
>
>outperforms:
>
>   x and True or False
>
>neither of which is as clear as:
>
>   bool(x)
>
Point. ;-)
(I actually thought to do not not x and bool(x) also crossed my mind, so
I'm not sure why I wound up with the above).

BTW, I imagine this is probably faster (and closer to the OP's approach),
at least for large option sets: (maybe needs comment like # not all None's ? ;-)

 >>> def get_options(opt):
 ...     values = vars(opt).values()
 ...     return values.count(None) != len(values)
 ...
 >>> opt = type('',(),{})()
 >>> get_options(opt)
 False
 >>> opt.a=None
 >>> get_options(opt)
 False
 >>> opt.b=None
 >>> get_options(opt)
 False
 >>> opt.c = 'option c'
 >>> get_options(opt)
 True
 >>> vars(opt)
 {'a': None, 'c': 'option c', 'b': None}

Regards,
Bengt Richter



More information about the Python-list mailing list