Still the __new__ hell ...

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Mar 19 10:39:49 EDT 2007


Jean-Paul Calderone a écrit :
> On Mon, 19 Mar 2007 13:17:11 +0100, Bruno Desthuilliers
>>
>> [snip]
>>
>> And what if it's a unicode string ?
>> The correct idiom here is:
>>                  if isinstance(year, basestring):
>>
>>>             year,month,day=map(int,string.split(year,'-'))
>>                         year, month, day = map(int, year.split('-'))
> 
> And what if it's another kind of string?

One that doesn't inherit from basestring ?

>  The correct idiom is:
> 
>   try:
>       parts = year.split('-')
>   except AttributeError:
>       # Handle int case
>   else:
>       year, month, day = map(int, parts)
> 
>>
>>>         if year < 100:
>>>             year += 2000
>>>         return date.__new__(cls,year,month,day)
>>>

And what if it's an object that has nothing to do with a string but 
happens to have a split() method ?-)

>> (snip)

Jean-Paul, you're of course right from a theoretical POV. Practically 
speaking, chances that such a method will ever be fed with a string-like 
object not deriving from basestring are IMVHO *very* low. While I 
usually raise a big warning flag when I spot a test against 
isinstance(), I'd say this is an example of the few cases where it's ok. 
  YMMV of course...



More information about the Python-list mailing list