Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A lightweight Traits like module

License

NotificationsYou must be signed in to change notification settings

ipython/traitlets

TestsDocumentation StatusTidelift

homehttps://github.com/ipython/traitlets
pypi-repohttps://pypi.org/project/traitlets/
docshttps://traitlets.readthedocs.io/
licenseModified 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 achange;
  • registering for receiving notifications when trait values change;
  • reading configuring values from files or from command linearguments - a distinct layer on top of traitlets, so you may usetraitlets without the configuration machinery.

Its implementation relies on thedescriptorpattern, and it is a lightweight pure-python alternative of thetraits library.

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

Installation

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

pip install traitlets

For adevelopment installation, clone this repository, change into thetraitlets root directory, and run pip:

git clone https://github.com/ipython/traitlets.gitcd traitletspip install -e.

Running the tests

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

Code Styling

traitlets has adopted automatic code formatting so you shouldn'tneed 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 installpre-commit locally, run the following::

pip install pre-commitpre-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 codeand tell you about any errors it couldn't fix automatically.You may also installblack integrationinto your text editor to format code automatically.

If you have already committed files before setting up the pre-commithook withpre-commit install, you can fix everything up usingpre-commit run --all-files. You need to make the fixing commityourself after that.

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

Usage

Any class with trait attributes must inherit fromHasTraits.For the list of available trait types and their properties, see theTrait Typessection 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, andshould return the default value. In this example, the_username_defaultmethod is decorated with@default('username'):

importgetpassfromtraitletsimportHasTraits,Unicode,defaultclassIdentity(HasTraits):username=Unicode()@default('username')def_username_default(self):returngetpass.getuser()

Callbacks when a trait attribute changes

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

To do something when a trait attribute is changed, decorate a method withtraitlets.observe().The method will be called with a single argument, a dictionary which containsan 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`):

fromtraitletsimportHasTraits,Integer,observeclassTraitletsExample(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 orcoercion logic. In addition, we can register custom cross-validatorsthat may depend on the state of other attributes. For example:

fromtraitletsimportHasTraits,TraitError,Int,Bool,validateclassParity(HasTraits):value=Int()parity=Int()@validate('value')def_valid_value(self,proposal):ifproposal['value']%2!=self.parity:raiseTraitError('value and parity should be consistent')returnproposal['value']@validate('parity')def_valid_parity(self,proposal):parity=proposal['value']ifparitynotin [0,1]:raiseTraitError('parity should be 0 or 1')ifself.value%2!=parity:raiseTraitError('value and parity should be consistent')returnproposal['value']parity_check=Parity(value=2)# Changing required parity and value together while holding cross validationwithparity_check.hold_trait_notifications():parity_check.value=1parity_check.parity=1

However, werecommend that custom cross-validators don't modify the stateof 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 copyrightover their contributions to IPython. But, it is important to note that thesecontributions are typically only changes to the repositories. Thus, the IPythonsource code, in its entirety is not the copyright of any single person orinstitution. Instead, it is the collective copyright of the entire IPythonDevelopment Team. If individual contributors want to maintain a record of whatchanges/contributions they have specific copyright on, they should indicatetheir copyright in the commit message of the change, when they commit thechange to one of the IPython repositories.

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

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

About

A lightweight Traits like module

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors104

    Languages


    [8]ページ先頭

    ©2009-2025 Movatter.jp