{
  "__type": "IngestedDoc",
  "__tag": 4010,
  "_content": {},
  "_ordered_sections": [],
  "item_file": null,
  "item_line": null,
  "item_type": null,
  "aliases": [],
  "example_section_data": {
    "__type": "Section",
    "__tag": 4015,
    "children": [],
    "title": [],
    "level": 0,
    "target": null
  },
  "see_also": [],
  "signature": null,
  "references": null,
  "qa": "using_traitlets",
  "arbitrary": [
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "In short, traitlets let the user define classes that have"
            }
          ]
        },
        {
          "__type": "BulletList",
          "__tag": 4053,
          "ordered": true,
          "start": 1,
          "children": [
            {
              "__type": "ListItem",
              "__tag": 4054,
              "children": [
                {
                  "__type": "Paragraph",
                  "__tag": 4045,
                  "children": [
                    {
                      "__type": "Text",
                      "__tag": 4046,
                      "value": "Attributes (traits) with type checking and dynamically computed    default values"
                    }
                  ]
                }
              ]
            },
            {
              "__type": "ListItem",
              "__tag": 4054,
              "children": [
                {
                  "__type": "Paragraph",
                  "__tag": 4045,
                  "children": [
                    {
                      "__type": "Text",
                      "__tag": 4046,
                      "value": "Traits emit change events when attributes are modified"
                    }
                  ]
                }
              ]
            },
            {
              "__type": "ListItem",
              "__tag": 4054,
              "children": [
                {
                  "__type": "Paragraph",
                  "__tag": 4045,
                  "children": [
                    {
                      "__type": "Text",
                      "__tag": 4046,
                      "value": "Traitlets perform some validation and allow coercion of new trait    values on assignment. They also allow the user to define custom    validation logic for attributes based on the value of other    attributes."
                    }
                  ]
                }
              ]
            }
          ]
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Using Traitlets"
        }
      ],
      "level": 0,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "At its most basic, traitlets provides type checking, and dynamic default value generation of attributes on "
            },
            {
              "__type": "CrossRef",
              "__tag": 4002,
              "value": "traitlets.HasTraits",
              "reference": {
                "__type": "RefInfo",
                "__tag": 4000,
                "module": "traitlets",
                "version": "*",
                "kind": "api",
                "path": "traitlets.traitlets:HasTraits"
              },
              "kind": "module"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " subclasses:"
            }
          ]
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "from traitlets import HasTraits, Int, Unicode, default\nimport getpass\n\n\nclass Identity(HasTraits):\n    username = Unicode()\n\n    @default(\"username\")\n    def _default_username(self):\n        return getpass.getuser()",
          "execution_status": null
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "class Foo(HasTraits):\n    bar = Int()\n\n\nfoo = Foo(bar=\"3\")  # raises a TraitError",
          "execution_status": null
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "TraitError: The 'bar' trait of a Foo instance must be an int,\nbut a value of '3' <class 'str'> was specified",
          "execution_status": null
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Default values, and checking type and value"
        }
      ],
      "level": 1,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "Traitlets implement the observer pattern"
            }
          ]
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "class Foo(HasTraits):\n    bar = Int()\n    baz = Unicode()\n\n\nfoo = Foo()\n\n\ndef func(change):\n    print(change[\"old\"])\n    print(change[\"new\"])  # as of traitlets 4.3, one should be able to\n    # write print(change.new) instead\n\n\nfoo.observe(func, names=[\"bar\"])\nfoo.bar = 1  # prints '0\\n 1'\nfoo.baz = \"abc\"  # prints nothing",
          "execution_status": null
        },
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "When observers are methods of the class, a decorator syntax can be used."
            }
          ]
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "class Foo(HasTraits):\n    bar = Int()\n    baz = Unicode()\n\n    @observe(\"bar\")\n    def _observe_bar(self, change):\n        print(change[\"old\"])\n        print(change[\"new\"])",
          "execution_status": null
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "observe"
        }
      ],
      "level": 1,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Validation and Coercion"
        }
      ],
      "level": 1,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "Each trait type ("
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "Int"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ", "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "Unicode"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ", "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "Dict"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " 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."
            }
          ]
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Custom Cross-Validation"
        }
      ],
      "level": 2,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "from traitlets import HasTraits, TraitError, Int, Bool, validate\n\n\nclass Parity(HasTraits):\n    data = Int()\n    parity = Int()\n\n    @validate(\"data\")\n    def _valid_data(self, proposal):\n        if proposal[\"value\"] % 2 != self.parity:\n            raise TraitError(\"data and parity should be consistent\")\n        return proposal[\"value\"]\n\n    @validate(\"parity\")\n    def _valid_parity(self, proposal):\n        parity = proposal[\"value\"]\n        if parity not in [0, 1]:\n            raise TraitError(\"parity should be 0 or 1\")\n        if self.data % 2 != parity:\n            raise TraitError(\"data and parity should be consistent\")\n        return proposal[\"value\"]\n\n\nparity_check = Parity(data=2)\n\n# Changing required parity and value together while holding cross validation\nwith parity_check.hold_trait_notifications():\n    parity_check.data = 1\n    parity_check.parity = 1",
          "execution_status": null
        },
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "Notice how all of the examples above return "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "proposal['value']"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ". Returning a value is necessary for validation to work properly, since the new value of the trait will be the return value of the function decorated by "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "@validate"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ". If this function does not have any "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "return"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " statement, then the returned value will be "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "None"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ", instead of what we wanted (which is "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "proposal['value']"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": ")."
            }
          ]
        },
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "However, we recommend that custom cross-validators don't modify the state of the HasTraits instance."
            }
          ]
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Basic Example: Validating the Parity of a Trait"
        }
      ],
      "level": 3,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "The "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "List"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " and "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "Dict"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " trait types allow the validation of nested properties."
            }
          ]
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "from traitlets import HasTraits, Dict, Bool, Unicode\n\n\nclass Nested(HasTraits):\n    value = Dict(\n        per_key_traits={\"configuration\": Dict(value_trait=Unicode()), \"flag\": Bool()}\n    )\n\n\nn = Nested()\nn.value = dict(flag=True, configuration={})  # OK\nn.value = dict(flag=True, configuration=\"\")  # raises a TraitError.",
          "execution_status": null
        },
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "However, for deeply nested properties it might be more appropriate to use an external validator:"
            }
          ]
        },
        {
          "__type": "Code",
          "__tag": 4050,
          "value": "import jsonschema\n\nvalue_schema = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"price\": {\"type\": \"number\"},\n        \"name\": {\"type\": \"string\"},\n    },\n}\n\nfrom traitlets import HasTraits, Dict, TraitError, validate, default\n\n\nclass Schema(HasTraits):\n    value = Dict()\n\n    @default(\"value\")\n    def _default_value(self):\n        return dict(name=\"\", price=1)\n\n    @validate(\"value\")\n    def _validate_value(self, proposal):\n        try:\n            jsonschema.validate(proposal[\"value\"], value_schema)\n        except jsonschema.ValidationError as e:\n            raise TraitError(e)\n        return proposal[\"value\"]\n\n\ns = Schema()\ns.value = dict(name=\"\", price=\"1\")  # raises a TraitError",
          "execution_status": null
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Advanced Example: Validating the Schema"
        }
      ],
      "level": 3,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "Sometimes it may be impossible to transition between valid states for a "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "HasTraits"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " instance by changing attributes one by one. The "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "hold_trait_notifications"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " context manager can be used to hold the custom cross validation until the context manager is released. If a validation error occurs, changes are rolled back to the initial state."
            }
          ]
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Holding Trait Cross-Validation and Notifications"
        }
      ],
      "level": 2,
      "target": null
    },
    {
      "__type": "Section",
      "__tag": 4015,
      "children": [
        {
          "__type": "Paragraph",
          "__tag": 4045,
          "children": [
            {
              "__type": "Text",
              "__tag": 4046,
              "value": "Finally, trait types can emit other events types than trait changes. This capability was added so as to enable notifications on change of values in container classes. The items available in the dictionary passed to the observer registered with "
            },
            {
              "__type": "InlineCode",
              "__tag": 4051,
              "value": "observe"
            },
            {
              "__type": "Text",
              "__tag": 4046,
              "value": " depends on the event type."
            }
          ]
        }
      ],
      "title": [
        {
          "__type": "Text",
          "__tag": 4046,
          "value": "Custom Events"
        }
      ],
      "level": 1,
      "target": null
    }
  ],
  "local_refs": []
}