Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this datetime subclass fail on Python 3?

Tags:

python-3.x

I recently was surprised to find that this code would run on Python 2.7 just fine but would fail on Python 3.

import datetime

class MyTime(datetime.datetime):
    def __new__(cls, year):
        ob = datetime.datetime.__new__(cls, year, 1, 1)
        return ob

class MySpecialTime(MyTime):
    def __init__(self, *args, **kwargs):
        super(MySpecialTime, self).__init__(*args, **kwargs)

MyTime(2013)
MySpecialTime(2013)

On Python 3.3, the final line crashes with this error:

Traceback (most recent call last):
  File "file.py", line 13, in <module>
    MySpecialTime(2013)
  File "file.py", line 10, in __init__
    super(MySpecialTime, self).__init__(*args, **kwargs)
TypeError: object.__init__() takes no parameters

What is different between Python 2 and 3 that causes this code to fail on 3 only? Hint - adding and __init__ method to MyTime fixes the issue. I'm not interested in correcting the error nor writing better code (I've done both of those already). Instead, I want to understand why this happened, and specifically why Python 3.3 behaves differently.

like image 947
Jason R. Coombs Avatar asked Jan 13 '13 02:01

Jason R. Coombs


1 Answers

This is the fallout of a decision taken five years ago and enforced now, with Python 3.3, namely: http://bugs.python.org/issue1683368

The __init__ that ends up being called is the one from object, and that one will not accept parameters - it's a design decision and its reasoning is outlined in the bugreport.

like image 59
t.dubrownik Avatar answered Oct 22 '22 22:10

t.dubrownik