Dispatch table of methods with various return value types

dn PythonList at DancesWithMice.info
Tue Nov 17 04:56:34 EST 2020


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.
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.
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)?
-- 
Regards =dn


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /