Executing functions within switch dictionary

前端 未结 3 1467
不知归路
不知归路 2020-12-18 18:58

I have encountered a problem when putting all the modules I\'ve developed into the main program. The switch dictionary I\'ve created can be seen below:

def T         


        
3条回答
  •  萌比男神i
    2020-12-18 19:17

    As noted, the functions will get invoked during dictionary construction. Besides that, there's two other issues I see here:

    • Redefining switcher during every invocation of the function Tank_Shape_Calcs, this generally isn't a good idea.
    • Requiring all arguments to be passed (due to their definition as positionals) when only a handful of them might be needed, this is why we have *args :-)

    If my understanding of what you're up to is correct, I'd move switcher outside the function, as a Tank_Shape to function object mapping:

    switcher = {
        0: vertical.Vertical_Tank,
        1: horiz.Horiz_Cylinder_Dished_Ends,
        2: strapping.Calc_Strapped_Volume,
        3: poly.Fifth_Poly_Calcs
    }
    

    Then, define Tank_Shape_Calcs to take the excess arguments as a tuple with *args:

    def Tank_Shape_Calcs(Tank_Shape, *args):
        return switcher.get(Tank_Shape, lambda *_: "ERROR: Tank type not valid")(*args)
    

    and invoke your function after .getting it.

    This also plays off Jean's trick to define a lambda in .get but does so with *_ in order to allow it to get called with many args (which are consequently ignored).

提交回复
热议问题