Is using a dictionary of lambda functions an acceptable way to write code?

Question:

I wanted to code a function that returns the number of days of a given month on a given year (for Project Euler 19). Of course it’s very easy to do this with if statements but, for the sheer pleasure of seeing such a way work in Python, I decided to use a dictionary with lambda-functions as values:

md={
    'jan':lambda y: 31,
    'feb':lambda y: 29 if ((y%400 == 0) or (y%4==0 and y%100)) else 28,
    'mar':lambda y: 31,
    'apr':lambda y: 30,
    'may':lambda y: 31,
    'jun':lambda y: 30,
    'jul':lambda y: 31,
    'aug':lambda y: 31,
    'sep':lambda y: 30,
    'oct':lambda y: 31,
    'nov':lambda y: 30,
    'dec':lambda y: 31
    }

def mdays(month, year):
    return md[month](year)

This works perfectly.

Now I’m wondering whether there are factual reasons why this would not be recommended, compared to for example a simple function with if statements.

Thanks in advance for your answers.

Asked By: Swifty

||

Answers:

You can just remove the strings so you don’t have to eval it:

md = {
    'jan': lambda y: 31,
    'feb': lambda y: 29 if ((y % 400 == 0) or (y % 4 == 0 and y % 100)) else 28,
    'mar': lambda y: 31,
    'apr': lambda y: 30,
    'may': lambda y: 31,
    'jun': lambda y: 30,
    'jul': lambda y: 31,
    'aug': lambda y: 31,
    'sep': lambda y: 30,
    'oct': lambda y: 31,
    'nov': lambda y: 30,
    'dec': lambda y: 31
}


def mdays(month, year):
    return md[month](year)

print(mdays('feb', 2400))

Previous comment:
Definitely not, when there’s such a simple way to do this:

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Answered By: Adid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.