Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80624

Re: Python Style Question

Newsgroups comp.lang.python
Date 2014-11-12 12:31 -0800
References <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com>
Message-ID <b3889a96-91da-40a0-bad0-bd315c8ed7c3@googlegroups.com> (permalink)
Subject Re: Python Style Question
From Anton <anton.schattenfeld@gmail.com>

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Python Style Question Anton <anton.schattenfeld@gmail.com> - 2014-11-12 12:31 -0800

csiph-web