Implement logic on object.attribute and object.attribute()

Chris Angelico rosuav at gmail.com
Sun Nov 24 08:05:50 EST 2013


On Sun, Nov 24, 2013 at 11:52 PM, Marc Aymerich <glicerinu at gmail.com> wrote:
> if I access to "object.attribute" I want to return the result of an
> HTTP GET request. However if i call "object.attribute()" I want an
> HTTP POST request to be executed.

That's fundamentally difficult, because object.attribute() first
evaluates object.attribute, then calls it. The only way you can have
that work, then, is if you have one version (calling it) do the POST
call, and something else (maybe conversion to str?) do the GET call.
But it's not going to be easy. I would recommend having both of them
done with a call; since a POST request will almost always include a
request body and a GET request almost never, I would be inclined to a
model like this:

def __call__(self, METHOD=None, **params):
    METHOD = method or ('POST' if params else 'GET')
    # proceed to use the given method

This way, you simply call it with no args for a GET, or with form
fill-out args for POST, and you can override if you want to (eg for a
PUT request, or doing something unusual like POST without data).

ChrisA



More information about the Python-list mailing list