dn <pythonl...@danceswithmice.info> writes: > On 17/11/2020 22:01, Loris Bennett wrote: >> Hi, >> >> I have a method for manipulating the membership of groups such as: >> >> def execute(self, operation, users, group): >> """ >> Perform the given operation on the users with respect to the >> group >> """ >> >> action = { >> 'get': self.get, >> 'add': self.add, >> 'delete': self.delete, >> } >> >> return action.get(operation)(users, group) >> >> The 'get' action would return, say, a dict of users attribute, whereas >> the 'add/delete' actions would return, say, nothing, and all actions >> could raise an exception if something goes wrong. >> >> The method which calls 'execute' has to print something to the terminal, >> such as the attributes in the case of 'get' and 'OK' in the cases of >> 'add/delete' (assuming no exception occurred). >> >> Is there a canonical way of dealing with a method which returns different >> types of data, or should I just make all actions return the same data >> structure so that I can generate a generic response? > > > Is the problem caused by coding the first step before thinking of the overall > task? Try diagramming or pseudo-coding the complete solution (with multiple > approaches), ie the operations AND the printing and exception-handling.
You could have a point, although I do have a reasonable idea of what the task is and coming from a Perl background, Python always feels a bit like pseudocode anyway (which is one of the things I like about Python). > Might it be more appropriate to complete not only the get but also its > reporting, as a unit. Similarly the add and whatever happens after that; and > the > delete, likewise. Currently I am already obtaining the result and doing the reporting in one method, but that makes it difficult to write tests, since it violates the idea that one method should, in general, just do one thing. That separation would seem appropriate here, since testing whether a data set is correctly retrieved from a database seems to be significantly different to testing whether the reporting of an action is correctly laid out and free of typos. > Otherwise the code must first decide which action-handler, and later, > which result-handler - but aren't they effectively the same decision? > Thus, is the reporting integral to the get (even if they are in > separate routines)? I think you are right here. Perhaps I should just ditch the dispatch table. Maybe that only really makes sense if the methods being dispatched are indeed more similar. Since I don't anticipate having more than half a dozen actions, if that, so an if-elif-else chain wouldn't be too clunky. Cheers, Loris -- This signature is currently under construction. -- https://mail.python.org/mailman/listinfo/python-list