[Python-ideas] strptime without second argument as an inverse to __str__
Ethan Furman
ethan at stoneleaf.us
Wed Aug 6 18:45:11 CEST 2014
On 08/06/2014 09:20 AM, Wolfgang Maier wrote:
> On 06.08.2014 17:42, Alexander Belopolsky wrote:
>>
>> On Wed, Aug 6, 2014 at 11:19 AM, Wolfgang Maier
>> <wolfgang.maier at biologie.uni-freiburg.de
>> <mailto:wolfgang.maier at biologie.uni-freiburg.de>>
>> wrote:
>>
>> What are the downsides of:
>>
>> dt = datetime.datetime.now() # assuming this works ;)
>> sdt = str(dt)
>> ndt = datetime.datetime(std)
>> print(dt == ndt)
>> #True
>>
>>
>> I'll refrain from mentioning "explicit is better than implicit" ;)
>>
>> It's just that it seems to be a design pattern of the datetime class
>> to provide alternative constructors as classmethods instead of doing
>> magic things in __new__ .
>>
>>
>> I don't think this is a "design pattern". In Python 2, having date(str)
>> constructor was blocked by some magic that is there to support unpickling:
>>
>> >>> from datetime import date
>> >>> date('\x07\xd0\x01\x01')
>> datetime.date(2000, 1, 1)
>>
>
> I see. None of my examples (fromtimestamp, utcfromtimestamp and now) involves string parsing though.
>
>> This is no longer an issue in Python 3.
>>
>> Note that if we allow date('2000-01-01'), this may become a more
>> readable and efficient alternative to date(2001, 1, 1).
>>
>
> One problem with this is the very first concern raised by Steven and Skip in this thread: choosing a string format that
> __new__ can deal with *would* lock you into this format.
> If later, for example, full-blown ISO 8601 or even just RFC 3339 parsing makes it into the module, wouldn't you rather
> want this to be done by __new__ when it sees a string ?
> Implementing the current proposal as a classmethod with its own name (once a good one is accepted) is a much more
> cautious approach.
>
> BTW, Terry's suggestion of datetime.fromstr(s) sounds very reasonable.
For my own classes I accept both year, month, day, ..., or a single string in __new__.
But for the stdlib I agree that .fromstr() is the better approach.
+1 for .fromstr()
--
~Ethan~
More information about the Python-ideas
mailing list