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


Groups > comp.lang.python > #80624 > unrolled thread

Re: Python Style Question

Started byAnton <anton.schattenfeld@gmail.com>
First post2014-11-12 12:31 -0800
Last post2014-11-12 12:31 -0800
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#80624 — Re: Python Style Question

FromAnton <anton.schattenfeld@gmail.com>
Date2014-11-12 12:31 -0800
SubjectRe: Python Style Question
Message-ID<b3889a96-91da-40a0-bad0-bd315c8ed7c3@googlegroups.com>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web