Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constant constraint not enforced in Union #1784

Open
k2bd opened this issue Apr 9, 2024 · 1 comment
Open

Constant constraint not enforced in Union #1784

k2bd opened this issue Apr 9, 2024 · 1 comment
Labels
component: core Issues related to the core library type: bug

Comments

@k2bd
Copy link
Contributor

k2bd commented Apr 9, 2024

Constant constraint is not enforced when initializing Union (came up in writing tests for #1298)

class TestClass(HasTraits):
    attribute = Union(None, Constant(123))

a = TestClass(attribute=456)  # No exception raised
a.attribute  # 456
@k2bd k2bd changed the title validate method of Constant is permissive; constraint not enforced in Union Constant constraint not enforced in Union initialization Apr 9, 2024
@k2bd k2bd changed the title Constant constraint not enforced in Union initialization Constant constraint not enforced in Union Apr 9, 2024
@k2bd
Copy link
Contributor Author

k2bd commented Apr 9, 2024

Sorry for the edits, I think there are multiple things going on here, which threw me off.


Scenario 1: Setting default_value on Union:

class TestClass(HasTraits):
    attribute = Union(None, Constant(123), default_value=55)

a = TestClass()
a.attribute  # 55

No validation -> I think this may be a need for some additional validation logic in Union's __init__. I think this isn't directly related to Constant but to a lack of validation in Union (though simply adding validation at the moment I think would cause issues specifically with Constant; see Scenario 2)


Scenario 2: Set value on an existing HasTraits object w/ Union trait

class TestClass(HasTraits):
    attribute = Union(None, Constant(123))

a = TestClass()
a.attribute = 456

a.attribute  # 456

I think the cause of this is that the validate method of Constant is permissive; doesn't use its setter logic:

class TestClass(HasTraits):
    attribute = Constant(123)

a = TestClass()
const_trait = a.traits()["attribute"]

const_trait.validate(a, "attribute", 456)  # 456

And this is used in Union to validate new values

This may have effects elsewhere too

@mdickinson mdickinson added type: bug component: core Issues related to the core library labels Apr 10, 2024
@k2bd k2bd mentioned this issue Apr 10, 2024
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: core Issues related to the core library type: bug
Projects
None yet
Development

No branches or pull requests

2 participants