Sunday, September 4, 2022

[SOLVED] Missing calendar module in python3.9 venv

Issue

I am trying to run a python application inside python3.9 virtualenv. But I am getting the following error:

AttributeError: module 'calendar' has no attribute 'monthlen'

This is how I setup the environment:

sudo apt install python3.9-venv
python3.9 -m venv .venv/
source  .venv/bin/activate

I could see that 'calendar' module is not loaded from the virtual env. Instead it's loaded from the system python installation:

>>> import calendar
>>> print(calendar.__file__)
/usr/lib/python3.9/calendar.py
>>> 

Looks like "calendar" module is supposed to be part of the python installation, but is not there in the virtual env (cant locate any files in the virtual env with name containing "calendar" ) and is not available via pip. How can I get the calendar module and any other standard inbuilt modules I might need later?


Solution

calendar.monthlen was an undocumented Python 3.7 function, that has been renamed to calendar._monthlen in Python 3.8 onwards to inform you that it's a "private" function and you should not rely on it.

The code is really just:

def _monthlen(year, month):
    return mdays[month] + (month == February and isleap(year))

Which is also basically the same as

calendar.monthrange(year, month)[1]

plus monthrange checks if month is a valid value.

So I would recommend you make your own function that does exactly the same instead of using "private" functions.

You can always check what's available with dir(module), e.g. dir(calendar):

['Calendar',
 'EPOCH',
 'FRIDAY',
 'February',
 'HTMLCalendar',       
 'IllegalMonthError',  
 'IllegalWeekdayError',
 'January',
 'LocaleHTMLCalendar', 
 'LocaleTextCalendar', 
 'MONDAY',
 'SATURDAY',
 'SUNDAY',
 'THURSDAY',
 'TUESDAY',
 'TextCalendar',       
 'WEDNESDAY',
 '_EPOCH_ORD',
 '__all__',
 '__builtins__',       
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_colwidth',
 '_locale',
 '_localized_day',
 '_localized_month',
 '_monthlen',
 '_nextmonth',
 '_prevmonth',
 '_spacing',
 'c',
 'calendar',
 'datetime',
 'day_abbr',
 'day_name',
 'different_locale',
 'error',
 'firstweekday',
 'format',
 'formatstring',
 'isleap',
 'leapdays',
 'main',
 'mdays',
 'month',
 'month_abbr',
 'month_name',
 'monthcalendar',
 'monthrange',
 'prcal',
 'prmonth',
 'prweek',
 'repeat',
 'setfirstweekday',
 'sys',
 'timegm',
 'week',
 'weekday',
 'weekheader']

And ofc there's also the docs: https://docs.python.org/3/library/calendar.html



Answered By - Mike Scotty
Answer Checked By - Timothy Miller (WPSolving Admin)