Is Python TypeErrors suited to a logic short circuit?

I have a function that performs a monthly task on one or more given days (for example, the first and 15th). To improve usability, I want users to simply pass one int when they only want it to happen one day per month or a list of indexes for multiple events per month.

monthly_event(days_of_month=1, event="paycheck") monthly_event(days_of_month=[1,15], event="bills", starting=date(2013,1,1)) 

Internally, the function will iterate over the list and do the same as for a single int.

Since "int" is not iterable, I need to do something to avoid using TypeError when the user just passes one int. I was surprised to find that using the "or" expression and using a short circuit did not work - TypeError is still happening. Here is an example:

 from datetime import date as date dt = date.today() days = 1 #days = [1,2] if dt.day == days or dt.day in days: print "GOOD" else: print "BAD" 

My first question is: didn’t I understand Python, or does the internal typecheck really happen on the entire line of code until the logical expression is short-circuited? It seems very strange.

My second question is: what is the pythonic way to do this? I would like to avoid explicit type checking in the "days" variable. Using try / catch instead simply inflates the code:

 try: if dt.day == days: print "GOOD" else: print "BAD" except TypeError: if dt.day in days: print "GOOD" else: print "BAD" 

Is there something obvious that I forgot?

+4
source share
1 answer

I believe the problem occurs when dt.day != days (and the short circuit is not accepted), Python will then try the dt.day in days expression and get a TypeError .

+6
source

All Articles