Question: When a variable should be set as a private class variable (e.g. _var) vs a class constant (e.g. VAR) vs a private class constant (e.g. _VAR)?

Question

When a variable should be set as a private class variable (e.g. _var) vs a class constant (e.g. VAR) vs a private class constant (e.g. _VAR)?

Answers 2
Added at 2016-11-25 19:11
Tags
Question

I'm finding myself unsure as to whether I should set certain variables that I use in my class as being private class variables (e.g. _var) vs class constant variables (e.g. VAR) vs a private class constant variable if such a thing is used (e.g. _VAR). I realize that this doesn't really matter in Python aside from convention, but would like to know which way is right (or more right).

For instance, let's say I have a certain variable for storing the regex pattern for height. Let's say I have no intention of modifying this anywhere in the class or elsewhere in the code, and in fact I only use it in one of the class methods, which should I go with then:

Option 1 - set as private class variable:

_height_pattern = r"""(#'##?"?)|#'"""

Option 2 - set as a constant class variable

HEIGHT_PATTERN = r"""(#'##?"?)|#'"""

Option 3 - set as a constant private class variable (not sure if such a thing exists or if I've ever seen a variable declaed in this for)

_HEIGHT_PATTERN = r"""(#'##?"?)|#'"""

Or perhaps some other option I haven't thought of. Note that in this case I've picked a variable that I'd think people would be able to make a good case for one way or the other. However, there are also other cases where I feel it'd be more vague. For instance, what if I have a random-seed variable (_SEED=2000?) whose changing wouldn't have a fundamental impact on functionality? Thus, if you can share some easy to follow rule of thumb, that'd be appreciated as well.

Answers
nr: #1 dodano: 2016-11-25 20:11

and in fact I only use it in one of the class methods

Then there's no doubt this shouldn't be a class variable at all. I would declare it inside the method as a constant.

However, I understand that your question is a bit more broad than this single example you gave, so let's imagine that this variable you speak of would be used in more than one method. In this case, as I also have never seen anything like option 3 (and hell it is ugly), you should go with option 2, as it's more important that your code says that this variable is not to be modified than to tell that it should not be accessed outside its class.

nr: #2 dodano: 2016-11-25 20:11

According to pep-0008 constants should be all captialized and use underscore when needed. Example HEIGHT_PATTERN.

As a more general note coding "style" for python can be found in pep 8 (see link above)

Source Show
◀ Wstecz