Skip to content

Instantly share code, notes, and snippets.

@e-roux
Last active November 30, 2020 22:18
Show Gist options
  • Save e-roux/26f128a1ea33d6cb5c3e7bcb8231e5b1 to your computer and use it in GitHub Desktop.
Save e-roux/26f128a1ea33d6cb5c3e7bcb8231e5b1 to your computer and use it in GitHub Desktop.
Python traitlets: example from documentation
# Example from traitlets documentation
from traitlets import Bool, HasTraits, Int, TraitError, observe, 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"]
@observe("parity")
def _observe_value(self, change):
print(
f"observing changes on { change['name'] }: { change['old'] } -> { change['new'] }"
)
parity_check = Parity(value=2)
# Changing required parity and value together while holding cross validation.
# Hold the custom cross validation until the context manager is released.
with parity_check.hold_trait_notifications():
parity_check.value = 1
parity_check.parity = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment