Pycharm (@property) and (@x.setter) autogeneration

Question:

I wonder whether there is some way of using Pycharm to automatically generate getter(@property) or setter for all my variables in a class.

If there is a way, can someone point it out ?


thanks! Actually I meant to generate (@property) and (@x.setter) automatically.

Asked By: Alex Gao

||

Answers:

There isn’t a way to do so. You can extract certain parts of code, but you cannot have pycharm generate getters and setters for you. There is no need either, since all variables are public, and the _var values, even though are treated as private variables can be altered as well.

EDIT (Change in question):

If you want to write less code when making getters and setters, then just use the props or the propsdsnippet in PyCharm.

Answered By: Games Brainiac

There is no need for it. The point of getters and setters is

  • limiting access (like making sth read-only)
  • maintaing API (so that you could change underlying fields or add some processing).

The first cannot be achieved in Python, and the second can be without using getters and setter everywhere.

If you had

class Person(object):

    def ___init__(self, full_name):
        self.full_name = full_name

and decided to have name and surname instead, you could then add

    @property
    def full_name(self):
        return self.name + " " + self.surname

    @full_name.setter
    def full_name(self, value):
        self.name, self.surname = value.split()

without breaking the API.

Just because Python doesn’t enforce private members doesn’t mean you have to do without them. But be warned that getters and setters are function calls and are much slower than direct member access.

PyCharm doesn’t offer a menu to create properties for all your private members but it has a live template for it: within your class (indentation must be correct) type prop and press enter. A stub of your read only property will appear.

I adopted my live template to easily generate a getter like property:
Open Settings (Ctrl+Alt+S) -> Editor -> Live Templates -> Python -> prop

@property
def $NAME$(self):
    return self.__$NAME$

The same for live template props for read write access:

@property
def $NAME$(self) -> $TYPE$:
    return self.__$NAME$

@$NAME$.setter
def $NAME$(self, $NAME$: $TYPE$):
    self.__$NAME$ = $NAME$
Answered By: Mr. Clear

I wrote a PyCharm Plugin that can generate getters and setters. It uses PyCharm’s live templates to generate them and automatically selects private variables. Not very pretty, but it gets the job done.

As others have said, Python usually lets variables be public, but there is always a time and a place.

Answered By: CJCrafter
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.