1

In order to avoid the overhead associated with the shelve module's writeback option I'm interested in putting together a shelf class that only accepts hashable values, with hashability being a proxy for immutability. So I'd like to subclass shelve.Shelf and override the __set__ method. The catch is that shelve.open can return one of a number of different classes (e.g., Dbfilenameshelf), and I'd like my code to allow shelve this flexibility.

Ideally a solution would have the following properties:

  1. No need to wrap every function that Shelf provides, as in: def keys(self): return self._shelf.keys()
  2. Will not break if Python adds new methods to Shelf or new subclasses of Shelf
  3. Avoiding fragility, by which I mean doing something complicated that could easily trip up someone (conceivably me) who is modifying or using the code months or years down the road. An example in this context would be reassigning Shelf.__set__, as in Shelf.__set__ = my_func. To me defining a new __getattr__ as @Winston hesitantly offers seems moderately fragile--I take it that's why he suggests it only with hesitation

Less important but still desirable would be:

  1. Consistent with object-oriented design principles. It seems to me that the new class here is a shelf, not that it has a shelf. And probably not both (it's not a shelf which contains another shelf)
2
  • 1
    What do you mean by "correct?"CommentedJul 7, 2014 at 22:08
  • This question has been edited in an attempt to fix the issues that led to it being put on hold. I'm posting as much here on the seeming advice of this answer
    – kuzzooroo
    CommentedJul 8, 2014 at 20:05

1 Answer 1

1

Don't subclass shelve.Self, instead define a new class with a constructor that that calls shelve.open. Implement the method of interest by calling the actual methods on the returned shelf object.

2
  • I believe this approach requires me to wrap every method of Shelf, like def keys(self): return self._shelf.keys(). Is that correct?
    – kuzzooroo
    CommentedJul 8, 2014 at 4:50
  • @kuzzooroo, well, you could override __getattr__ to forward everything to _shelf. I'd figure you probably only need a couple of the methods for what's actually useful in a shelf, and so I'd just implement those directly.CommentedJul 8, 2014 at 5:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.