Skip to main content

Traitlets

Tests Test downstream projects Documentation Status Tidelift

home https://github.com/ipython/traitlets
pypi-repo https://pypi.org/project/traitlets/
docs https://traitlets.readthedocs.io/
license Modified BSD License

Traitlets is a pure Python library enabling:

  • the enforcement of strong typing for attributes of Python objects (typed attributes are called "traits");
  • dynamically calculated default values;
  • automatic validation and coercion of trait attributes when attempting a change;
  • registering for receiving notifications when trait values change;
  • reading configuring values from files or from command line arguments - a distinct layer on top of traitlets, so you may use traitlets without the configuration machinery.

Its implementation relies on the descriptor pattern, and it is a lightweight pure-python alternative of the traits library.

Traitlets powers the configuration system of IPython and Jupyter and the declarative API of IPython interactive widgets.

Installation

For a local installation, make sure you have pip installed and run:

pip install traitlets

For a development installation, clone this repository, change into the traitlets root directory, and run pip:

git clone https://github.com/ipython/traitlets.git
cd traitlets
pip install -e .

Running the tests

pip install "traitlets[test]"
py.test traitlets

Code Styling

traitlets has adopted automatic code formatting so you shouldn't need to worry too much about your code style. As long as your code is valid, the pre-commit hook should take care of how it should look.

To install pre-commit locally, run the following::

pip install pre-commit
pre-commit install

You can invoke the pre-commit hook by hand at any time with::

pre-commit run

which should run any autoformatting on your code and tell you about any errors it couldn't fix automatically. You may also install black integration into your text editor to format code automatically.

If you have already committed files before setting up the pre-commit hook with pre-commit install, you can fix everything up using pre-commit run --all-files. You need to make the fixing commit yourself after that.

Some of the hooks only run on CI by default, but you can invoke them by running with the --hook-stage manual argument.

Usage

Any class with trait attributes must inherit from HasTraits. For the list of available trait types and their properties, see the Trait Types section of the documentation.

Dynamic default values

To calculate a default value dynamically, decorate a method of your class with @default({traitname}). This method will be called on the instance, and should return the default value. In this example, the _username_default method is decorated with @default('username'):

import getpass
from traitlets import HasTraits, Unicode, default

class Identity(HasTraits):
    username = Unicode()

    @default('username')
    def _username_default(self):
        return getpass.getuser()

Callbacks when a trait attribute changes

When a trait changes, an application can follow this trait change with additional actions.

To do something when a trait attribute is changed, decorate a method with traitlets.observe(). The method will be called with a single argument, a dictionary which contains an owner, new value, old value, name of the changed trait, and the event type.

In this example, the _num_changed method is decorated with @observe(`num`):

from traitlets import HasTraits, Integer, observe

class TraitletsExample(HasTraits):
    num = Integer(5, help="a number").tag(config=True)

    @observe('num')
    def _num_changed(self, change):
        print("{name} changed from {old} to {new}".format(**change))

and is passed the following dictionary when called:

{
  'owner': object,  # The HasTraits instance
  'new': 6,         # The new value
  'old': 5,         # The old value
  'name': "foo",    # The name of the changed trait
  'type': 'change', # The event type of the notification, usually 'change'
}

Validation and coercion

Each trait type (Int, Unicode, Dict etc.) may have its own validation or coercion logic. In addition, we can register custom cross-validators that may depend on the state of other attributes. For example:

from traitlets import HasTraits, TraitError, Int, Bool, validate

class Parity(HasTraits):
    value = Int()
    parity = Int()

    @validate('value')
    def _valid_value(self, proposal):
        if proposal['value'] % 2 != self.parity:
            raise TraitError('value and parity should be consistent')
        return proposal['value']

    @validate('parity')
    def _valid_parity(self, proposal):
        parity = proposal['value']
        if parity not in [0, 1]:
            raise TraitError('parity should be 0 or 1')
        if self.value % 2 != parity:
            raise TraitError('value and parity should be consistent')
        return proposal['value']

parity_check = Parity(value=2)

# Changing required parity and value together while holding cross validation
with parity_check.hold_trait_notifications():
    parity_check.value = 1
    parity_check.parity = 1

However, we recommend that custom cross-validators don't modify the state of the HasTraits instance.

Release build:

Releases should be automatically build and pushed to Pypi when a tag is marked and pushed to GitHub.

$ pip install build
$ python -m build .

Metadata

Release files for traitlets 5.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for traitlets 5.4.0
File Size Uploaded
traitlets-5.4.0.tar.gz 134.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for traitlets 5.4.0
File Interpreter ABI Platform
traitlets-5.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 241.5 kB

Release files / traitlets-5.4.0.tar.gz

Download URL traitlets-5.4.0.tar.gz
Size 134.3 kB
Tags Source
SHA-256 checksum
How to use checksums
3f2c4e435e271592fe4390f1746ea56836e3a080f84e7833f0f801d9613fec39
BLAKE2b-256 checksum
How to use checksums
a24d1f59a77fba6e8e9feea7a168652030564089d66c06492ba5670e73b0e078
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.6

Release files / traitlets-5.4.0-py3-none-any.whl

Download URL traitlets-5.4.0-py3-none-any.whl
Size 107.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93663cc8236093d48150e2af5e2ed30fc7904a11a6195e21bab0408af4e6d6c8
BLAKE2b-256 checksum
How to use checksums
7d288f4757d68ee7c46e0733dda81595f1bd107fda7bc0c6a577912387e87d86
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.6

Release history Release notifications | RSS feed

5.16.0

2 release files

5.14.3

2 release files

5.14.2

2 release files

5.14.0

2 release files

5.13.0

2 release files

5.12.0

2 release files

5.10.1

2 release files

5.10.0

2 release files

5.9.0

2 release files

5.8.1

2 release files

5.8.0

2 release files

5.7.1

2 release files

5.7.0

2 release files

5.6.0

2 release files

5.5.0

2 release files

This release

5.4.0 This release

2 release files

5.3.0

2 release files

5.2.2

3 release files

5.2.1

2 release files

5.2.0

2 release files

5.1.1

2 release files

5.1.0

2 release files

5.0.5

2 release files

5.0.4

2 release files

5.0.3

2 release files

5.0.2

2 release files

5.0.1

1 release file

5.0.0

2 release files

4.3.3

2 release files

4.3.2

2 release files

4.3.1

2 release files

4.3.0

2 release files

4.2.2

3 release files

4.2.1

3 release files

4.2.0

3 release files

4.1.0

3 release files

4.0.0

2 release files

4.0.0.dev

0.0.2

1 release file

0.0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page