polarbits
polarbits

Reputation: 197

How to simplify 2 conditions that rely on one another but lead to the same result?

I have a function that accepts an integer year, but I also want the user to be able to pass in the string 'ALL' and still be able to get something back.

I have this ugly piece of code right now:

if type(year) != str or (type(year) == str and year.upper() != 'ALL'):
    total_results = self.filterResultsByYear(total_results, year, year2)

Results are filtered by default to the current year, and can be filtered by other years, but if the user wants to not filter, they have to pass in 'all' for the year.

The reason I wrote the above abomination is if I just have if year.upper() != 'ALL' I get a TypeError if I pass in an integer. If I put if type(year) != str and year.upper() != 'ALL' I still get the same error. The above code looks really ugly and I wanted to make it more pythonic. What tools do I have to do this?

Upvotes: 0

Views: 48

Answers (1)

Alexander
Alexander

Reputation: 109726

Depending on what total_results and year2 are and how you'd like to handle them:

try:
    year = int(year)
    total_results = self.filterResultsByYear(total_results, year, year2)
except ValueError:
    if not isinstance(year, (str, unicode)):
        raise  # Not string, unicode or coercible to an integer.
    if year.lower() == 'all':
        # Your logic here.
    else:
        # String but not 'all'.  Exception handling.

Bye the way, to check for class equivalency one uses isinstance(object, class) or isinstance(object, (class 1, class 2, ...)).

Upvotes: 1

Related Questions