Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41041
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Switch statement |
| Date | 2013-03-10 18:02 -0400 |
| References | <mailman.3155.1362925062.2939.python-list@python.org> <513ca430$0$6512$c3e8da3$5496439d@news.astraweb.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3170.1362952971.2939.python-list@python.org> (permalink) |
On 3/10/2013 11:18 AM, Steven D'Aprano wrote:
> On Sun, 10 Mar 2013 14:16:27 +0000, Joseph L. Casale wrote:
>
>> I have a switch statement composed using a dict:
>>
>>
>> switch = {
>> 'a': func_a,
>> 'b': func_b,
>> 'c': func_c
>> }
>> switch.get(var, default)()
>>
>>
>> As a result of multiple functions per choice, it migrated to:
>>
>>
>>
>> switch = {
>> 'a': (func_a1, func_a2),
>> 'b': (func_b1, func_b2),
>> 'c': (func_c, )
>> }
>>
>>
>>
>> for f in switch.get(var, (default, )):
>> f()
>>
>>
>> As a result of only some of the functions now requiring unique
>> arguments, I presume this needs to be migrated to a if/else statement?
>> Is there a way to maintain the switch style with the ability in this
>> scenario to cleanly pass args only to some functions?
>
>
> The dict-as-switch-statement pattern only works when the functions all
> take the same argument(s). Otherwise, you need to check which function
> you are calling, and provide the right arguments.
If, for instance, the functions take either 0 or 1 arg and the 1 arg is
always the same, an alternative to the other suggestions is to look at
the signature in an if statement. In 3.3 this is relatively ease, as
inspect.signature(func) returns a signature object. There are more
complicated paths in earlier versions.
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Switch statement "Joseph L. Casale" <jcasale@activenetwerx.com> - 2013-03-10 14:16 +0000
Re: Switch statement Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-10 15:18 +0000
RE: Switch statement "Joseph L. Casale" <jcasale@activenetwerx.com> - 2013-03-10 17:51 +0000
Re: Switch statement Terry Reedy <tjreedy@udel.edu> - 2013-03-10 18:02 -0400
csiph-web