I have the following code to set the y and x axis limits from the command line in a script which eventually calls matplotlib (here, ax
is a matplotlib axes
object, but it shouldn't really matter, and p
is an ArgumentParser
instance):
p.add_argument('--ylim', help='Set the y axis limits explicitly (e.g., to cross at zero)', type=float, nargs='+')
p.add_argument('--xlim', help='Set the x axis limits explicitly', type=float, nargs='+')
# more stuff
if args.ylim:
if (len(args.ylim) == 1):
ax.set_ylim(args.ylim[0])
elif (len(args.ylim) == 2):
ax.set_ylim(args.ylim[0], args.ylim[1])
else:
sys.exit('provide one or two args to --ylim')
if args.xlim:
if (len(args.xlim) == 1):
ax.set_xlim(args.xlim[0])
elif (len(args.xlim) == 2):
ax.set_xlim(args.xlim[0], args.xlim[1])
else:
sys.exit('provide one or two args to --xlim')
If you believe in DRY that probably makes your eyes burn: these two blocks are identical except that xlim
replaces ylim
everywhere in the second.
How can I refactor this to remove the duplication? Some kind of limit setting function which I call twice seems obvious, but how do I pass the fact that I want to call set_ylim
in one case and set_xlim
in other, for example?
Note that calling the script without specifying either or both of the --*lim
arguments is totally valid and should behave as-if the corresponding set_*lim
functions were never called (that is, as in the code above - although if the functions are called but with the identical effect as the sample that is fine as well).