22

We have numerous python classes that do not seem to need __init__, initialising them empty is either perfectly acceptable or even preferable. PyLint seems to think this is a bad thing. Am I missing some insight into why having no __init__ is a Bad Smell? Or should I just suppress those warnings and get over it?

Pete
  • 1,241
  • 2
  • 9
  • 21
  • Do these classes have no attributes at all, or do you add attributes after the object is created? –  Feb 01 '12 at 17:48
  • Either. In the former case, I can see that that is itself a bad smell, but not oen I want ot go into right now. In the latter case, I'd rather have the Attribute Exception if I try using it before meaningful initialisation. – Pete Feb 01 '12 at 17:50
  • would you have some code and pylint output to show? Pylint usually complains about __init__ for some reason. If really not, then it needs a fix :) – sthenault Feb 02 '12 at 08:29
  • @sthenault, I don't think it is a Pylint error as such, it is correct that there is no `__init__`. I was more asking whether I was using a horribly non-Pythonic idiom, which I think I am not. – Pete Feb 06 '12 at 12:01

2 Answers2

15

What are you using these classes for?

If they are just a grouping of functions that do not need to maintain any state, there is no need for an __init__() but it would make more sense to just move all of those functions into their own module.

If they do maintain a state (they have instance variables) then you should probably have an __init__() so that those variables can be initialized. Even if you never provide values for them when the class is created, it is generally a good idea to have them defined so that your method calls are not referencing instance variables that may or may not exist.

That being said, if you don't need an __init__(), feel free to ignore that warning.

edit: Based on your comment, it seems like you are fine with the AttributeError you will get on referencing variables before initialization. That is a perfectly fine way to program your classes so in that case ignoring the warning from PyLint is reasonable.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
2

Usually you will at least use the __init__() method to initialize instance variables. If you are not doing this, then by all means turn off that warning.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Well, when we are talking about a pytest class it should have no init according to the pytest docs. So, configuring a pylinrc to ignore W0232 for the test path seems reasonable – Peter Kahn Jul 12 '19 at 13:39