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)
  • 1
    What do you mean by "correct?" – Robert Harvey Jul 7 '14 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 Jul 8 '14 at 20:05
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.

| improve this answer | |
  • I believe this approach requires me to wrap every method of Shelf, like def keys(self): return self._shelf.keys(). Is that correct? – kuzzooroo Jul 8 '14 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. – Winston Ewert Jul 8 '14 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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