Skip to content

Instantly share code, notes, and snippets.

@hvy
Last active November 15, 2019 04:46
Show Gist options
  • Save hvy/56d460e97aee6d1f53ac5cf0c26eaec1 to your computer and use it in GitHub Desktop.
Save hvy/56d460e97aee6d1f53ac5cf0c26eaec1 to your computer and use it in GitHub Desktop.
Optuna public/private visibility coding style
## Add `_` prefix to the names of private interfaces.
Interfaces in `optuna`, i.e. submodules, classes and attributes are either public, private for internal use in `optuna` or private for internal use within a parcitular class. Private interfaces are not part of the public API and are not expected to be directly used by the library user. They are only meant for internal use in `optuna`. This reserves them for future changes and allows modifications without breaking compatibility. It is therefore important to clearly communciate whether an interfaces is public or private and `optuna` distinigushes between them as follows.
Reference: https://docs.python.org/3/tutorial/classes.html#private-variables.
### Good
```python
def public_function(): # Used by users.
pass
def _private_function(): # Used internally in `optuna`.
pass
class PublicClass: # Used by users.
def __init__(self):
self.public_attr = 1 # Accessed by users.
self._private_attr = 2 # Accessed internally in `optuna`.
self.__class_private_attr = 3 # Accessed only within this class.
def public_method(self):
pass
def _private_method(self):
pass
def __class_private_method(self):
pass
class _PrivateClass: # Used internally in `optuna`.
def __init__(self):
self.private_attr = 1 # Accessed internally in `optuna`.
self._private_attr = 2 # Same as above.
self.__class_private_attr = 3 # Accessed only within this class.
def private_method(self):
pass
def _private_method(self):
pass
def __class_private_method(self):
pass
```
### Bad
```python
def __bad_function(): # Do not define functions prefixed with `__`.
pass
class __BadClass: # Do not define classes prefixed with `__`.
pass
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment