Class/instance attribute naming convention in python

2.6k views Asked by At

Looking at PEP8 one can find naming conventions for variables, functions, constants...but I have not been able to get a clear view about which is the naming convention for both class level and instance level attributes.

Currently, my own style brings a bit of the constant vs variable distinction into class and instance levels, such as this:

  • Class level attributes meant to be read as constant or default values follow the constant convention: DEFAULT_VALUE.
  • Class level attributes meant to be shared and modified by any instance of the class or any inheriting class are also named following the constant conventions: COMMON_ATTRIBUTE.
  • Attributes defined directly by the instances and used/visible only by them follow the variable conventions: instance_attribute

Here you have a very silly example showing these use cases:

class Parent(object):

    DEFAULT = 1
    COUNTER = 0    # counts times default value has been accessed

    def __init__(self, value=None):
        self.value = value or self.DEFAULT

    def is_default(self):
        return self.value is self.DEFAULT

    def get_value(self):
        if self.is_default():
            Parent.COUNTER += 1
        return self.value + self.COUNTER


class Child(Parent):
    """Use Parent's value + 1."""
    def __init__(self, value=None):
        self.value = (value or self.DEFAULT) + 1

And here's a (silly) use case:

>>> child = Child()
>>> child.is_default()
False
>>> parent = Parent(2)
>>> parent.is_default()
False
>>> default_parent = Parent()
>>> default_parent.is_default()
True
>>> child.get_value()
2
>>> parent.get_value()
2
>>> default_parent.get_value()
2
>>> child.get_value()
3
>>> default_parent.get_value()
3
>>> parent.get_value()
4

My question at the end is: Does this adhere to the (official) standards or is it violating any other convention that I may have overlooked?

0

There are 0 answers