Last active
November 30, 2020 22:18
-
-
Save e-roux/26f128a1ea33d6cb5c3e7bcb8231e5b1 to your computer and use it in GitHub Desktop.
Python traitlets: example from documentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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