Function Defaults - avoiding unneccerary combinations of arguments at input

Terry Reedy tjreedy at udel.edu
Wed Mar 25 16:19:35 EDT 2015


On 3/25/2015 3:50 PM, Ivan Evstegneev wrote:

> Googled a bit, and found only one, a "ValueError" exception, but still don't
> understand how it should be implemented in my case.
>
> Should my code look like this one:
>
> def  my_fun(history=False, built=False, current=False, topo=None,
> full=False, file=None):
> 	try:
> 		if currnet and full:
> 			do something_1
> 		elif current and file:
> 			do something_2
> 		elif history and full and file:
> 			do something_3
> 	
> 	except ValueError:
> 		print("No valid input! Please try again ...")

You need to raise ValueError, not try to catch one that never occurs.

def  my_fun(history=False, built=False, current=False, topo=None,
full=False, file=None):
     if current and full:
         do something_1
     elif current and file:
         do something_2
     elif history and full and file:
         do something_3
     else:
         raise ValueError("not a valid combination of arguments")

My answer does not negate the possibility that Ian is correct that you 
are trying to do too much in one function.  But I did want to point out 
that there are stdlib precedents for excluding invalid argument 
combinations.  However, in those cases, only a small proportion of 
combinations are invalid and if the function were split, most of the 
code would be duplicated.

Here is an mutually exclusive combo that is *not* flagged: passing both 
'-' (read from stdin) and 'file.py' to python on the command line.  The 
first wins and the second is ignored.  '-i -' is redundant and ignored.


-- 
Terry Jan Reedy




More information about the Python-list mailing list