Underscores in Python

There are some conventions and implementation details that make use of underscores in Python, which is an interesting topic that's worthy of analysis.

Like we mentioned previously, by default all attributes of an object are public. Consider the following example to illustrate this:

>>> class Connector:...     def __init__(self, source):...         self.source = source...         self._timeout = 60... >>> conn = Connector("postgresql://localhost")>>> conn.source'postgresql://localhost'>>> conn._timeout60>>> conn.__dict__{'source': 'postgresql://localhost', '_timeout': 60}

Here, a Connector object is created with source, and it starts with two attributes—the aforementioned source and timeout. The former is public, and the latter private. ...

Get Clean Code in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.