Ok I am programing a way to interface with Grooveshark (http://grooveshark.com). Right now I have a class Grooveshark and several methods, one gets a session with the server, another gets a token that is based on the session and another is used to construct api calls to the server (and other methods use that). Right now I use it like so…. Note uses twisted and t.i.defer in twisted
g = Grooveshark()
d = g.get_session()
d.addCallback(lambda x: g.get_token())
## and then something like.... ##
g.search("Song")
I find this unpythonic and ugly sense even after initializing the class you have to call two methods first or else the other methods won’t work. To solve this I am trying to get it so that the method that creates api calls takes care of the session and token. Currently those two methods (the session and token methods) set class variables and don’t return anything (well None). So my question is, is there a common design used when interfacing with sites that require tokens and sessions? Also the token and session are retrieved from a server so I can’t have them run in the init method (as it would either block or may not be done before a api call is made)
If so, then why not put the
get_sessionpart in your class’s__init__? If it always must be performed before anything else, that would seem to make sense. Of course, this means that calling the class will still return a yet-unusable instance — that’s kind of inevitable with asynchronous, event-drive programming… you don’t “block until the instance is ready for use”.One possibility would be to pass the callback to perform as an argument to the class when you call it; a more Twisted-normal one would be to have
Groovesharkbe a function which returns a deferred (you’ll add to the deferred the callback to perform, and call it with the instance as the argument when that instance is finally ready to be used).