[Python-ideas] strptime without second argument as an inverse to __str__

Andrew Barnert abarnert at yahoo.com
Thu Aug 7 01:55:25 CEST 2014


On Aug 6, 2014, at 8:42, Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:

> On Wed, Aug 6, 2014 at 11:19 AM, Wolfgang Maier <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)
> 
> 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).

More readable maybe, but more efficient? You're doing the same work, plus string parsing; you're eliminating two parameters (but only if you use *args) at the cost of three locals; by any measure it's less efficient.

But more readable is the important part. In isolation it's readable, the question is whether the added complexity (in the docs and in people's heads) of an effectively-overloaded constructor is worth the cost.

Given that, unlike all the obvious parallel cases (int, float, etc.) this constructor will not accept the repr, I'm not sure the answer comes out the same. But maybe it does. 

I'm -0 on this, +1 on Terry's fromstr, +0 on strptime and strftime both accepting no arguments, -1 on only strptime, -0.5 on fromisostring/fromisoformat, and -1 on remembering any of the other ideas in this thread well enough to comment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140806/64b980cc/attachment.html>


More information about the Python-ideas mailing list