CodexBloom - Programming Q&A Platform

advanced patterns when using a custom property setter in Python 3.10

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
python properties error-handling Python

Hey everyone, I'm running into an issue that's driving me crazy. I'm working with an scenario with a custom property setter in my class. I have a class that manages a configuration object, and I want to ensure that whenever a specific attribute is set, it gets validated. However, I'm experiencing an unexpected behavior where the validation logic is not being executed as I would expect. Here’s a simplified version of my code: ```python class Config: def __init__(self): self._value = None @property def value(self): return self._value @value.setter def value(self, new_value): if not isinstance(new_value, int): raise ValueError('Value must be an integer') self._value = new_value config = Config() try: config.value = 'not an int' except ValueError as e: print(e) print(config.value) ``` Initially, I thought that when I try to assign a non-integer value, it should raise a ValueError, which it does. However, after catching the exception, I noticed that `config.value` is still set to `None` rather than remaining unchanged. I expected it to preserve the previous value instead of setting it to `None`. I’ve also tried adding a print statement within the setter to see if it’s being triggered, but it only outputs the behavior message without any indication that the value was changed. Is there a way to ensure that the previous value remains intact when an assignment fails? I'm using Python 3.10, and I've checked that my Python environment is properly set up for this version. Any insights on how to achieve this would be greatly appreciated. How would you solve this? Any ideas what could be causing this?