Package: traitlets
Traitletshomehttps://github.com/ipython/traitletspypi-repohttps://pypi.org/project/traitlets/docshttps://traitlets.readthedocs.io/licenseModified BSD LicenseTraitlets 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 thedescriptorpattern, and it is a lightweight pure-python alternative of thetraitslibrary.Traitlets powers the configuration system of IPython and Jupyter
and the declarative API of IPython interactive widgets.InstallationFor a local installation, make sure you havepip installedand run:pipinstalltraitletsFor adevelopment installation, clone this repository, change into thetraitletsroot directory, and run pip:gitclonehttps://github.com/ipython/traitlets.gitcdtraitlets
pipinstall-e.Running the testspipinstall"traitlets[test]"py.testtraitletsCode Stylingtraitletshas 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 installpre-commitlocally, run the following::pip install pre-commit
pre-commit installYou can invoke the pre-commit hook by hand at any time with::pre-commit runwhich should run any autoformatting on your code
and 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-commit
hook withpre-commit install, you can fix everything up usingpre-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 manualargument.UsageAny 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 valuesTo 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_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 changesWhen 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 withtraitlets.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_changedmethod 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 coercionEach trait type (Int,Unicode,Dictetc.) 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: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=1However, werecommendthat custom cross-validators don't modify the state
of the HasTraits instance.About the IPython Development TeamThe 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 PolicyIPython 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.