Can PyCharm automatically generate __eq__() and __hash__() implementations?
You can create a Live Template
Under File->Settings->Editor->Live TemplatesLook for PythonClick + to add, I then name mine "class" and make sure to add a context in the gui for Python files.
The Template Text :
class $class_name$: """$class_docstring$""" def __init__(self, $args$): """$init_docstring$""" pass def __eq__(self, $other$): if not isinstance($other$, $class_name$): return NotImplemented elif self is $other$: return True else: return self.$eq_field$ == $other$.$eq_field$ def __hash__(self, ): pass $END$
I left my "Options" -> "Expand with" section set to "Default (Tab)"After this point, when you type "class" you can use Tab auto-complete to insert the live template. Your cursor will be bounced into any section included as a variable in the Live Template Text.
More complicated, i.e. list type, variables don't appear to be supported by LiveTemplate. For instance, conditionals in the live template text, or list expansions, don't appear to be available.
Select the class
and then do one of:
- Press
Alt-Insert
Right Click -> Generate
Menu -> Code -> Generate
Maybe the concept of data classes may also be interesting to you?
https://docs.python.org/3/library/dataclasses.html
The annotation implicitly generates default methods. I know this is not an answer to your question (because one can not actually see the generated code) but could possibly help with the reason why you are asking.