0

I have a class Book, which has a property editable, along with others:

class Book():

    def __init__(self, name, ..., editable=True):
        self.name = name
        ...
        self.editable = editable

Book has methods get_details(), set_details() and delete().

If editable is set to False, I want to raise an Exception in set_details() and delete(), stating that the Book is not editable.

I have gone through the Python docs but I haven't been able to find anything similar to a Not-Editable exception.

Is raising a custom exception the best way to do this, or can anyone suggest another workaround?

Thanks!

codeandfire
  • 445
  • 2
  • 9

2 Answers2

1

As far as I know python does not have this type of exception. You can define custom Exception class of your own.

class NotEditableException(Exception):
    def __init__(self,message="Not editable"):
        super(NotEditableException,self).__init__(message)

Now you can raise your exception the following way.

if not self.editable:
    raise NotEditableException("This is your error message");
Mitiku
  • 5,337
  • 3
  • 18
  • 35
1

I would recommend using the property decorator for restricting mutable attributes. For instance consider:

class Book(object):
  """My book object is a wrapper for details"""

  class Details(object):
    """My details object"""

  def __init__(self):
    self._details = Details()

  @properties
  def details(self):
     return self._details

trying to run

book = Book()
book.details = new_details

will raise an AttributeError. To turn this "off and on" using the editable flag, you could add the following decorated method:

  @details.setter
  def details(self, new_details):
    if self._editable:
      self._details = new_details
    else:
      raise AttributeError("Attribute cannot be set when Book is not editable.")

As for delete, Python's garbage collector should cleanup old variables as long as you're smart with scope :)

For more on properties and setters, check out this. If you are planning on making the "book" immutable after a certain point, I would recommend looking into a factory design pattern (where you would programmatically construct the book class before exposing it) opposed to turning on and off a flag.

Dylan Madisetti
  • 775
  • 7
  • 22