python - Defining variables efficiently according to a parameter that may take several values -


i have function defines , returns variables a , b depending on value of parameter orientation.

        def myfunc(orientation, l, w):               if orientation == 1:                 = -w                 b = l             elif orientation == 2:                 = -l                 b = w             elif orientation == 3:                 = -w                 b = -l             elif orientation == 4:                 = -l                 b = -w             elif orientation == 5:                 = w                 b = l             elif orientation == 6:                 = l                 b = w             elif orientation == 7:                 = w                 b = -l             elif orientation == 8:                 = l                 b = -w              return a, b 

my question is: there more compact and/or more efficient way same thing? , if there better way, it?

a way use dictionary . example -

def myfunc(orientation, l, w):     return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),              4: (-l, -w), 5: (w, l), 6: (l, w),              7: (w, -l), 8: (l, -w) }[orientation] 

please note evaluates possible values in dictionary , selects appropriate value return based on orientation key. should not use method if want values evaluated when needed.

demo -

>>> def myfunc(orientation, l, w): ...     return {1: (-w, l), 2: (-l, w), 3: (-w, -l), ...             4: (-l, -w), 5: (w, l), 6: (l, w), ...             7: (w, -l), 8: (l, -w)}[orientation] ... >>> myfunc(3,3,4) (-4, -3) 

the above end in keyerror , if key not found. if possible call function orientation not found in dictionary, can use .get(key, default) , make return default other default value. example -

def myfunc(orientation, l, w):     return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),              4: (-l, -w), 5: (w, l), 6: (l, w),              7: (w, -l), 8: (l, -w) }.get(orientation) #this returns `none` if orientation not found in dictionary. use `.get(orientation, defaultval)` other default value. 

Comments