enthought / enthought/traits

Provide API for explicitly overriding trait static default

Open
#1,369 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
462
Forks
90
PR merge metrics
No merged PRs in 30d

Description

Take this code in Mayavi for example:
```
class MayaviUIPlugin(Plugin):
# Extension point Ids.
VIEWS = 'envisage.ui.workbench.views'
PERSPECTIVES = 'envisage.ui.workbench.perspectives'
PREFERENCES_PAGES = 'envisage.ui.workbench.preferences_pages'
ACTION_SETS = 'envisage.ui.workbench.action_sets'
BANNER = 'envisage.plugins.ipython_shell.banner'

# The plugins name.
name = 'Mayavi UI plugin'

# Our ID.
id = 'mayavi_ui'
```
(From https://github.com/enthought/mayavi/blob/9c128635943e28513776dec68492ffd0268c28d1/mayavi/plugins/mayavi_ui_plugin.py#L65-L79)

The `name` and `id` are in fact, traits of `Str()` types defined on the base class. By assigning a new string value to it in the class definition, the static default value is changed. Consequently, one can write something like this:
```
@observe("name")
def name_updated(self, event):
....
```

However, the `VIEWS`, `PERSPECTIVES` etc., they are NOT defined as traits types. They are in fact, just plain class attributes there. Just by reading the class definition, it is hard to see the distinction.

Overriding default trait value by direct assignment is widely used, partly because it is convenient, partly because it frees the subclass from having to worry about the specific details of the trait type definition on the base class. However the language syntax used by this feature conflates with defining a plain Python class attribute. The outcome is obscured code: Developers new or accustomed to traits could easily overlook the distinction.

This issue proposes a callable for explicitly overriding static default value in class definition, e.g. like this:
```
class BaseClass(HasTraits):
name = Str()

class Subclass(BaseClass):
name = default_to("New Name")
```

Such callable may return a simple data object for the meta class to consume. Not only this will make code more explicit, this will also allow an alternative solution for fixing https://github.com/enthought/traits/issues/411

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.