-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 29/10/2014 12:01, Rafael Romero Carmona wrote: > 2014-10-29 12:25 GMT+01:00 Martin Kemp <martin.k...@ingg.com>: On > 29/10/2014 10:45, Anton wrote: >>>> Let's say I have an incoming list of values *l*. Every >>>> element of *l* can be one of the following options: 1) an >>>> integer value 2) a string in form of '<int_value>', e.g. '7' >>>> 3) a string with a json serialization of an integer value, >>>> e.g. '"7"' 4) something else that should be ignored >>>> >>>> I need to transform this list into another list with values >>>> from options 1)-3) coerced to int. The code below should do >>>> this. >>>> >>>> >>>> Variant 1 === >>>> >>>> values = [] for c in l: # Case 1) or 2) try: c_int = int(c) >>>> except ValueError: pass else: values.add(c_int) continue >>>> >>>> # Case 3) try: c_int = int(json.loads(c)) except ValueError: >>>> pass else: values.add(c_int) continue >>>> >>>> === >>>> >>>> Is this code ugly? Does it follow EAFP? Am I missing >>>> something in language best practice? >>>> >>>> Or maybe below is more preferable way with a nested >>>> try...except clause? >>>> >>>> Variant 2 === values = [] for c in l: # Case 1) or 2) try: >>>> c_int = int(c) except ValueError: # Case 3) try: c_int = >>>> int(json.loads(c)) except ValueError: pass else: >>>> values.add(c_int) continue else: values.add(c_int) continue >>>> === >>>> >>>> Thanks, Anton. >>>> >>>> > > Your first example is perfectly fine and is EAFP > > >> Actually it doesn't work because there is no add function and it >> doesn't catch the TypeError function to ignore other exceptions >> than ValueError. Doesn't it? I tested in Python 2.7.6 and 3.4. > > Personally, I prefer to avoid nesting when it's not necessary. > >> -- https://mail.python.org/mailman/listinfo/python-list
Ah ok, style-wise it was fine. - -- Martin Kemp (martin.k...@ingg.com) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iQEcBAEBAgAGBQJUUOD+AAoJEJ0Re0UIDzSu1KQIAK6aCMOv4VqOjmm/zoQrmzLf UGBCLwtHrnDkbXFAIweTSFiM1uf9TDaRpJqY1IrPbJHI4/EAP0Hu07nyx3V6HgzM /+Wb3DkpjW+JQoVqDSGzE/dTPJcU3/b1/EWWpbu72JHplqz9laEAFt9muWyDPs9u kDgM06mDd50lsi83W3i0H1iGL6YbLtsik+/x4G4mMjdq1o9BvRpUjkIiOx7yJ/BR OYzdudltXGqlXcToufHTU2lUv2C0RoHHNO4kytiLoUekCBdGE+Jy/6gQq/AKQu4G 0RYjCOnKNgugfdmDuHi0julPtTEzc+MdY/CcPob4cyy8RDzfQGklGKHP7f9+SJs= =hjWU -----END PGP SIGNATURE----- -- https://mail.python.org/mailman/listinfo/python-list