OnDemandPhoto can be written

OnDemandPhoto can be written differently by overriding __getattr__

I did this recently to cache an RPC call that returned many different fields.

it basically did something like

  1. def _get_remote_info(self):
  2. if self._remote_info:
  3. return self._remote_info
  4. self._remote_info = do_rpc_call_stuff(self.id)
  5. return self._remote_info
  6. remote_info = property(_get_remote_info)
  7. def __getattr__(self, name):
  8. if name in ('foo', 'bar','baz','lots','of','fields'):
  9. return self.remote_info[name]
  10. ...
  11. #alternatively: if name in self.remote_info:
  12. # return self.remote_info[name]

This way, if the remote method was changed to return more values, I only had to change one line, or zero if I used the alternate method. The only downside I see to this is that the autogenerated docs for the class won't include any mention of these fields.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockcode>
  • Lines and paragraphs break automatically.
  • You may post block code using <blockcode [type="language"]>...</blockcode> tags.
More information about formatting options