Using Traitlets¶
Any class with traitlet attributes must inherit from HasTraits
.
You then declare the traitlets on the class like this:
from traitlets import HasTraits, Int, Unicode
class Requester(HasTraits):
url = Unicode()
timeout = Int(30) # 30 will be the default value
For the available traitlet types and the arguments you can give them, see Trait Types.
Dynamic default values¶
To calculate a default value dynamically, give your class a method named
_traitname_default
. This will be called on the instance,
and should return the default value. For example:
import getpass
class Identity(HasTraits):
username = Unicode()
def _username_default(self):
return getpass.getuser()
Callbacks when traitlets change¶
To do something when a traitlet is changed, define a method named
_traitname_changed
. This can have several possible signatures:
-
class
traitlets.
TraitletsCallbacksExample
¶
You can also add callbacks to a trait dynamically:
Note
If a traitlet with a dynamic default value has another value set before it is
used, the default will not be calculated.
Any callbacks on that trait will will fire, and old_value will be None
.