Python Style Question

Anton anton.schattenfeld at gmail.com
Wed Nov 12 21:31:28 CET 2014


On Thursday, October 30, 2014 4:10:23 AM UTC-7, Steven D'Aprano wrote:
> I don't particularly like either version. I prefer this:
> 
> def load_int(obj):
>     if isinstance(obj, int):
>         # Case 1), an int, e.g. 7
>         return obj

>     elif isinstance(obj, str):
>         # Case 2) and 3), a str or JSON serialised int.
>         # E.g. '7' or '"7"'.
>         try:
>             return int(obj)
>         except ValueError:
>             return int(json.loads(obj))
>     raise TypeError('require int or str, got %s' % type(obj).__name__)

This will definitely work, but then I don't see a benefit of EAFP and duck-typing: 
Let's say I have a class 
class FakeInt(object):
   def __int__(self):
      return 42

In this case:
>>> fi = FakeInt()
>>> isinstance(fi, int)
False
>>> int(fi)
42

So probably I need to rephrase 1) something, that I can cast to int.

Same for 
>     elif isinstance(obj, str):
As long as it behaves like string (can be some sort if bytearray). For particularly this case, it will probably won't happen, but again, it looks like an overloaded function with strongly typed argument.

or a functional form:

> def tolerant_load_int(obj, default=None):
>     try:
>         return load_int(obj)
>     except (ValueError, TypeError):
>         return default

> values = [n for n in map(tolerant_load_int, l) if n is not None]

> # alternative to using map
> values = [n for n in (tolerant_load_int(obj) for obj in l) if n is not None] 

I like the idea of wrapping it up in a function and being able to use it in these functional forms.




More information about the Python-list mailing list