README.md
1# Traitlets
2
3[![Tests](https://github.com/ipython/traitlets/actions/workflows/tests.yml/badge.svg)](https://github.com/ipython/traitlets/actions/workflows/tests.yml)
4[![Test downstream projects](https://github.com/ipython/traitlets/actions/workflows/downstream.yml/badge.svg)](https://github.com/ipython/traitlets/actions/workflows/downstream.yml)
5[![Documentation Status](https://readthedocs.org/projects/traitlets/badge/?version=latest)](https://traitlets.readthedocs.io/en/latest/?badge=latest)
6
7| | |
8|---------------|----------------------------------------|
9| **home** | https://github.com/ipython/traitlets |
10| **pypi-repo** | https://pypi.org/project/traitlets/ |
11| **docs** | https://traitlets.readthedocs.io/ |
12| **license** | Modified BSD License |
13
14Traitlets is a pure Python library enabling:
15
16- the enforcement of strong typing for attributes of Python objects
17 (typed attributes are called *"traits"*);
18- dynamically calculated default values;
19- automatic validation and coercion of trait attributes when attempting a
20 change;
21- registering for receiving notifications when trait values change;
22- reading configuring values from files or from command line
23 arguments - a distinct layer on top of traitlets, so you may use
24 traitlets without the configuration machinery.
25
26Its implementation relies on the [descriptor](https://docs.python.org/howto/descriptor.html)
27pattern, and it is a lightweight pure-python alternative of the
28[*traits* library](https://docs.enthought.com/traits/).
29
30Traitlets powers the configuration system of IPython and Jupyter
31and the declarative API of IPython interactive widgets.
32
33## Installation
34
35For a local installation, make sure you have
36[pip installed](https://pip.pypa.io/en/stable/installing/) and run:
37
38```bash
39pip install traitlets
40```
41
42For a **development installation**, clone this repository, change into the
43`traitlets` root directory, and run pip:
44
45```bash
46git clone https://github.com/ipython/traitlets.git
47cd traitlets
48pip install -e .
49```
50
51## Running the tests
52
53```bash
54pip install "traitlets[test]"
55py.test traitlets
56```
57
58## Usage
59
60Any class with trait attributes must inherit from `HasTraits`.
61For the list of available trait types and their properties, see the
62[Trait Types](https://traitlets.readthedocs.io/en/latest/trait_types.html)
63section of the documentation.
64
65### Dynamic default values
66
67To calculate a default value dynamically, decorate a method of your class with
68`@default({traitname})`. This method will be called on the instance, and
69should return the default value. In this example, the `_username_default`
70method is decorated with `@default('username')`:
71
72```Python
73import getpass
74from traitlets import HasTraits, Unicode, default
75
76class Identity(HasTraits):
77 username = Unicode()
78
79 @default('username')
80 def _username_default(self):
81 return getpass.getuser()
82```
83
84### Callbacks when a trait attribute changes
85
86When a trait changes, an application can follow this trait change with
87additional actions.
88
89To do something when a trait attribute is changed, decorate a method with
90[`traitlets.observe()`](https://traitlets.readthedocs.io/en/latest/api.html?highlight=observe#traitlets.observe).
91The method will be called with a single argument, a dictionary which contains
92an owner, new value, old value, name of the changed trait, and the event type.
93
94In this example, the `_num_changed` method is decorated with ``@observe(`num`)``:
95
96```Python
97from traitlets import HasTraits, Integer, observe
98
99class TraitletsExample(HasTraits):
100 num = Integer(5, help="a number").tag(config=True)
101
102 @observe('num')
103 def _num_changed(self, change):
104 print("{name} changed from {old} to {new}".format(**change))
105```
106
107and is passed the following dictionary when called:
108
109```Python
110{
111 'owner': object, # The HasTraits instance
112 'new': 6, # The new value
113 'old': 5, # The old value
114 'name': "foo", # The name of the changed trait
115 'type': 'change', # The event type of the notification, usually 'change'
116}
117```
118
119### Validation and coercion
120
121Each trait type (`Int`, `Unicode`, `Dict` etc.) may have its own validation or
122coercion logic. In addition, we can register custom cross-validators
123that may depend on the state of other attributes. For example:
124
125```Python
126from traitlets import HasTraits, TraitError, Int, Bool, validate
127
128class Parity(HasTraits):
129 value = Int()
130 parity = Int()
131
132 @validate('value')
133 def _valid_value(self, proposal):
134 if proposal['value'] % 2 != self.parity:
135 raise TraitError('value and parity should be consistent')
136 return proposal['value']
137
138 @validate('parity')
139 def _valid_parity(self, proposal):
140 parity = proposal['value']
141 if parity not in [0, 1]:
142 raise TraitError('parity should be 0 or 1')
143 if self.value % 2 != parity:
144 raise TraitError('value and parity should be consistent')
145 return proposal['value']
146
147parity_check = Parity(value=2)
148
149# Changing required parity and value together while holding cross validation
150with parity_check.hold_trait_notifications():
151 parity_check.value = 1
152 parity_check.parity = 1
153```
154
155However, we **recommend** that custom cross-validators don't modify the state
156of the HasTraits instance.
157
158### Release build:
159
160Releases should be automatically build and pushed to Pypi when a tag is marked and pushed to GitHub.
161
162```bash
163$ pip install build
164$ python -m build .
165```
166