Python 2.7 warning: __init__ not compatible to __new__

Viewed 3768

I have a class defined in Python 2.7 like this:

from future.builtins import object


class Point(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

In PyCharm, this gives a warning in the __init__ line:

Signature is not compatible to __new__.

I don't understand what this warning is telling me. Can someone give an example where this warning would rightfully catch an error or can this warning be turned off?

There's a PyCharm thread for this, but it doesn't help me: https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000254530-PyCharm-init-Signature-is-not-compatible-to-new-

2 Answers

I suffered from the same problem and found the solution in here.

As discussed in the above link, a direct solution is to remove your Pycharm config directory ("/home/username/.PyCharm2018.3" for me). However, it would remove all your other configs too. Finally, I just fix the problem by removing the rule from inspections. You can find the rule in the Pycharm Setting window (see the figure as follow). enter image description here

This is a PyCharm bug; you can disable the warning via Xiong-Hui's post. Basically __new__ is a method that is called before __init__ with the same arguments when a class is constructed, so their signatures must be compatible (both functions must be able to be invoked with the same arguments) or the class cannot be instantiated. For example, here is a code snippet for which PyCharm correctly applies the warning:

class Test(object):
    def __new__(cls, arg1):
        return super().__new__(cls)

    def __init__(self):
        pass

Attempting to create the class with Test() will throw a TypeError since __new__ expects an argument, but creating the class with Test('something') will also throw a TypeError since __init__ doesn't expect any arguments, making it impossible to construct the class. Normally this is never an issue because the default implementation of __new__ in object accepts an arbitrary number of arguments, but if you define __new__ yourself you will need to be careful that the signatures remain compatible so the class can actually be constructed, which is the purpose of the warning.

Related