Implement logic on object.attribute and object.attribute()
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Nov 24 10:11:40 EST 2013
On Mon, 25 Nov 2013 01:37:12 +1100, Chris Angelico wrote:
> class Magic_HTTP_Thing:
> @property
> def attribute(self):
> result = CallableString(self.do_get())
> result.function = lambda: self.do_put()
> return result
> def do_get(self):
> # Do a HTTP GET request.
> print("Doing the GET call, please wait...")
> time.sleep(1)
> return "Get stuff"
> def do_put(self):
> # Do a HTTP PUT request.
> print("Doing the PUT call, please wait...")
> time.sleep(1)
> return "Put stuff"
>
> (PUT or POST, makes no difference; I think you were looking for POST,
> but Steven wrote PUT here so I'll use that for simplicity)
Oops, did I screw that bit up? Sorry.
One possible solution here is to cache the GET so it only occurs once.
def do_get(self):
# Do a HTTP GET request.
if hasattr(self, "_result"):
result = self._result
else:
print("Doing the GET call, please wait...")
time.sleep(1)
result = self._result = "Get stuff"
return result
You can give the cache a timestamp as well, in case you need to
invalidate the cache once it reaches a certain age. I'll leave that as an
exercise.
--
Steven
More information about the Python-list
mailing list