Is there any situation where it makes sense to define a python property, where getting (not setting) it would raise an exception? I don't think this ever happens for fields in classes, hence the question.

Or is always better in these cases to use a method instead?

closed as too broad by gnat, Martijn Pieters, user40980, user53019, Bart van Ingen Schenau Sep 22 '14 at 11:29

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What kind of exceptions? Certainly there are good reasons a property might raise NotImplementedError, AttributeError, etc. – Jace Browning Sep 19 '14 at 18:00
  • Lets say ones used more often in methods, KeyError, ValueError. – simonzack Sep 19 '14 at 18:01
  • @simonzack: What makes you think KeyError and ValueError are used more often in methods? – Martijn Pieters Sep 19 '14 at 18:10
  • 1
    recommended reading: Why is asking a question on “best practice” a bad thing? – gnat Sep 19 '14 at 18:12
  • 2
    @simonzack: There are different ways of wording a design pattern question. The term 'best practice' is like a red flag to a bull; your question is too much devoid of detail to avert said bull. – Martijn Pieters Sep 19 '14 at 18:32

I've created properties that raise exceptions in situations where I didn't want __init__ to raise exceptions and/or I wanted to delay processing.

class Identifier:

    def __init__(self, value):
        self._value = value

    def prefix(self):
        # ...
        # parse prefix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return prefix

    def suffix(self):
        # ...
        # parse suffix from self._value
        # raise ValueError is provided value cannot be parsed
        # ...
        return suffix

Not the answer you're looking for? Browse other questions tagged or ask your own question.