Using Double Underscores in Python, and the Black Death

OK maybe that title is sensationalistic.

A lot of people erroneously use double underscores to simulate “private” members, because double underscores invokes code mangling and makes those members harder to reference outside the class. However, it does not actually make them inaccessible.

Most of the time, it mainly adds a road bump to unit testing.

Really the double underscore mangling mechanism is to hide those members from subclasses that you don’t want clobbering the values inadvertently. Name mangling isn’t intended to hide the member from other programmers. The mangling scheme is simple, and referencing the variables anyway is easy.

Single underscore is the common convention for internal members. That’s saying, we’re all adults here, and although you can see it, this variable is intended for internal use. If you reference it, there’s no guarantee it will still be there in future versions.

The Pep8 doc talks about that, and says use of the double underscores for variables and functions should really be rare.

Advertisements

Leave a comment

Filed under design patterns, opinionizing, python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s