Python @ DjangoSpin

Object Oriented Python: Naming Convention of Variables/Attributes

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Naming Convention of Variables/Attributes in Python

Naming Convention of Variables/Attributes in Python

There are 4 conventions followed while naming variables in Python:

  1. Dunder attributes/Magic attributes such as __doc__, __name__ etc. are named with double underscores wrapped around the attribute name. It is general consensus to use the dunder attributes that Python is shipped with, and not create new ones.
  2. Variables/Attributes intended for private use by the class or module are prefixed with a single underscore e.g. _attr. Note that this is merely a convention, naming an attribute this way does not make it unusable by external classes and modules. It is merely a hint for fellow developers.
  3. Variables/Attributes intended for public use should be named in lower case i.e. variable_name. Note that this is also a convention only, you need not follow it strictly. You can opt for camelCasing as well, like I have done in examples all across the djangoSpin website. The important thing is that you know that this is a popular convention, and while writing professional Python code, you should use lower case variable names with underscores rather than camel casing.
  4. Variables/Attributes that are intended for private use by the class or module and not open for subclassing are named with double underscores in the beginning i.e. __variable_name. These can be accessed using a special syntax as shown below.
>>> class Man(object):
	def __init__(self):
		self.var_one = 1			# public variable
		self._var_two = 2			# private variable, open for subclassing and external use
		self.__var_three = 3		# private variable, not open for subclassing and external use
		self.__var_four__ = 4		# dunder variable

		
>>> ethan = Man()
>>> ethan.__dict__
{'_var_two': 2, '__var_four__': 4, 'var_one': 1, '_Man__var_three': 3}

>>> _Man__var_three
Traceback (most recent call last):
    _Man__var_three
NameError: name '_Man__var_three' is not defined

>>> Man._Man__var_three
Traceback (most recent call last):
    Man._Man__var_three
AttributeError: type object 'Man' has no attribute '_Man__var_three'

>>> ethan._Man__var_three			# correct syntax to access a private variable which is not open for subclassing and external use
3

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply