A calendar question

I have a list of month abbreviations, matching output of calendar.month_abbr. Given a month, say Feb, I would like to find month number. I’d expect this to work:

calendar.month_abbr.index('Feb')

but it fails:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[86], line 1
----> 1 calendar.month_abbr.index('Feb')

AttributeError: '_localized_month' object has no attribute 'index'

Is there a reason why index is not implemented, for an object that looks like a list?
I can write a one-liner expression to get what I want, is there a better way?

[n for n, m in enumerate(calendar.month_abbr) if m == 'Feb'][0]

Maybe that is the way to do it

list(calendar.month_abbr[:]).index('Feb')

2

Just found out that calendar.month_abbr[:] is a list, explicit conversion is not needed.

I often treat this discussion forum as a substitute for a yellow rubber duck. Mostly I find the answer before pressing the Create Thread button. I hope you don’t mind the noise.

The reason is probably that this class has not been touched in 20 years. I can’t think of a good reason to not make them (_localized_month and _localized_day) subclass collections.abc.Sequence which would provide .index for no real work.

1 Like

I did try it. One import, two line change.

calendar.month_name.index('February')
2

Should this thread be moved to Ideas?

Does this work in different locales?

If you find the answer before posting, then great! (I’ve had the same thing, too, at times.) And if you find it after posting - that’s also fine, you post a followup, and we have a short and simple thread. Oh, who am I kidding… no, we have a thread that, like most threads, goes off on tangents. Yep, I think you just contributed a perfectly acceptable few posts to this Discourse :smiley:

Works for me:

>>> locale.setlocale(locale.LC_ALL, ['fr_CA', 'utf8'])
'fr_CA.UTF-8'
>>> calendar.month_abbr[4]
'avr'
>>> calendar.month_abbr.index('avr')
4
>>> 

I was asking if calendar.month_name.index('February') would work if the user changes the locale. It would be safe to do that if the locale does not change, but it would raise an exception if the locale does change.

(I am trying to have a pre-ideas discussion, so feel free to create a thoughtful proposal.)

If the month name is not valid in the current locale, an exception is raised in the current implementation and the proposed one, by @MegaIng, not me. I don’t know why it should not. The difference is in error messages:

>>> calendar.month_abbr.index('Apr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen _collections_abc>", line 1063, in index
ValueError
>>> calendar.month_abbr[:].index('Apr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'Apr' is not in list

A better message would be Apr is not a valid month abbreviation.