Reputation: 352
I wonder if there is any convention regarding constructor in Python. If I have a constructor doing nothing, I can basically not writing it and everything will work just fine. However when I'm using Pycharm, it is recommending me (warning) to write an empty constructor:
__init__:
pass
I have not find anything regarding this problem in the PEP8. I am wondering if Pycharm just come out with a new convention or if there is a reason behind that ?
Thanks.
Upvotes: 3
Views: 2862
Reputation: 17234
I keep seeing this when I make a tiny, ad hoc class. I use this warning as a cue:
I forgot to derive the class from something sensible.
For example, an exception class that I would use to raise CustomException
.
No:
class CustomException:
pass
Yes:
class CustomException(Exception):
pass
Because Exception
defines an __init__
method, this change makes the warning go away.
Another example, a tiny class that doesn't need any member variables. The new style object (explicit in Python 2, implicit in Python 3) is derived from class object
.
class SettClass(object)
pass
Similarly, the warning goes away because object
has an __init__
method.
Or just disable the warning:
# noinspection PyClassHasNoInit
class StubbornClass:
pass
Upvotes: 1
Reputation: 1469
I agree with the sentiment to not write unnecessary code. The warning is probably there to help speed up development since most classes probably have an init and this will remind you to write it ahead of time.
It is possible to customize or suppress this warning in Settings -> Editor -> Inspections -> Python -> "Class has no __init__
method"
Upvotes: 3
Reputation: 35139
I think it's opinion based, but I will share rules that I try to follow: 1. Declare all instance variables in constructor, even if they are not set yet
def __init__(self, name):
self.name = name
self.lname = None
Do not do any logic in the constructor. You will benefit from this when will try to write unittests.
And of course if it's not necessary dont' add it.
Upvotes: 4
Reputation: 16711
Don't add a constructor if it doesn't do anything. Some editors like to warn you for some silly things. Eclipse for example, warns you when variables are initialized but not used later on or when classes don't have a serializable id. But that's Java. If your program will run without it, then remove the constructor.
Upvotes: 1