[Tutor] if ... else shorthand form ?

Dave Kuhlman dkuhlman at rexx.com
Sat Feb 9 19:10:12 CET 2008


On Sat, Feb 09, 2008 at 09:21:41AM +0000, dave selby wrote:
> Hi all,
> 
> Returning to python after a brief affair with C++, I have the following code ...
> 
>                 if (items.has_keys('snapshot_interval')):
>                     self.snap_init[i] = items['snapshot_interval']
>                 else:
>                     self.snap_init[i] = 0
> 
> I thought Python had a shorthand version of something like ....
> 
>                 self.snap_init[i] =
> (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0

For this specific task, if I understand it correctly, there is an
easy and Pythonic idiom:

    self.snap_init[i] = items.get('snapshot_interval', 0)

See: http://docs.python.org/lib/typesmapping.html

For mappings/dictionaries:

    a.get(k[, x])

is equivalent to:

    a[k] if k in a, else x

- (another) Dave    


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list