Pythonic way to do strategy design pattern,avoid use switch base on string compare Here are two functions, which are quite similar. The type of dtIndex is pandas DatetimeIndex and the only difference is the i.dayofyear part. There are days of week, month of year, week of month, week of year I still need to implement.

def extract_day_of_year(dtIndex):
    dayofyear_arr = []
    for i in dtIndex:
        dayofyear_arr.append(i.dayofyear)
    return dayofyear_arr

def extract_day_of_month(dtIndex):
    dayofmonth_arr = []
    for i in dtIndex:
        dayofmonth_arr.append(i.dayofmonth)
    return dayofmonth_arr


Is there a "Pythonic" way than switch according to an additional str parameter?
Yes. The most flexible approach would use getattr.

def extract(attr, datetimeindex):
    return [getattr(x, attr) for x in datetimeindex]

# Now, for example:
extract_day_of_year = partial(extract, attr='dayofyear')

# or
def extract_day_of_month(datetimeindex):
    return extract('dayofmonth', datetimeindex)


Alternatively with attrgetter:

def extract(attr, datetimeindex):
    return map(attrgetter(attr), datetimeindex)


I've also converted the for loop into a list comprehension (first) or map() (second), both of which spare you from needing to name a temporary variable.