• Stars
    star
    617
  • Rank 72,724 (Top 2 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created almost 11 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight Traits like module

Traitlets

Tests 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.

About the IPython Development Team

The IPython Development Team is the set of all contributors to the IPython project. This includes all of the IPython subprojects.

The core team that coordinates development on GitHub can be found here: https://github.com/jupyter/.

Our Copyright Policy

IPython uses a shared copyright model. Each contributor maintains copyright over their contributions to IPython. But, it is important to note that these contributions are typically only changes to the repositories. Thus, the IPython source code, in its entirety is not the copyright of any single person or institution. Instead, it is the collective copyright of the entire IPython Development Team. If individual contributors want to maintain a record of what changes/contributions they have specific copyright on, they should indicate their copyright in the commit message of the change, when they commit the change to one of the IPython repositories.

With this in mind, the following banner should be used in any source code file to indicate the copyright and license terms:

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

More Repositories

1

ipython

Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
Python
16,302
star
2

ipyparallel

IPython Parallel: Interactive Parallel Computing in Python
Jupyter Notebook
2,590
star
3

xkcd-font

The xkcd font
Python
1,113
star
4

ipython-in-depth

IPython and Jupyter in-depth Tutorial, first presented at PyCon 2012
Jupyter Notebook
928
star
5

ipykernel

IPython Kernel for Jupyter
Python
646
star
6

ipynb

Package / Module importer for importing code from Jupyter Notebook files (.ipynb)
Jupyter Notebook
245
star
7

pickleshare

File system based database that uses python pickles
Python
70
star
8

ipython-website

IPython website sources. Any fixes to the website should be done on this repository.
HTML
50
star
9

ipython-doc

Old builds of all the documentation for IPython's various releases, plus current development tree.
HTML
37
star
10

rlipython

Readline Interface for IPython 5.4+
Python
32
star
11

disp

Providing default representations of common objects in Python land
Jupyter Notebook
20
star
12

matplotlib-inline

Inline Matplotlib backend for Jupyter
Jupyter Notebook
19
star
13

salt-states-nbviewer

Salt States for nbviewer
Scheme
19
star
14

front-to-back

Talk about IPython frontends and backends for PyData SV 2014
Jupyter Notebook
18
star
15

talks

Talks and demonstration notebooks about IPython, to be used by anyone (all materials CC-BY licensed)
Python
17
star
16

marketing

Marketing materials for IPython: logos, banners, stickers, etc.
Jupyter Notebook
13
star
17

ipython_genutils

Vestigial IPython utilities: DO NOT USE
Python
11
star
18

ipython-ansible-jenkins

[Deprecated] Ansible playbook for our Jenkins server
10
star
19

ipython.github.com

Auto-generated sphinx version of the IPython website. Since this is an auto-generated directory, do *not* submit pull requests against this repository. The actual sources are in the ipython-website repository.
HTML
10
star
20

comm

Python Comm implementation for the Jupyter kernel protocol
Python
9
star
21

paper-notebook2013

A paper about the IPython Notebook written in 2013
8
star
22

mozfest2014

Introduction to the IPython Notebook at MozFest 2014
Shell
5
star
23

sloan-2013-reports

Progress reports for the Sloan 2013-14 grant.
Python
5
star
24

usersurveys

Materials for and results from user surveys
Python
3
star
25

.github

1
star