Skip to content

Fix KeyError when active_user_count missing from API response#2

Open
johntrandall wants to merge 1 commit intoPyprohly:mainfrom
johntrandall:fix/active-user-count-keyerror
Open

Fix KeyError when active_user_count missing from API response#2
johntrandall wants to merge 1 commit intoPyprohly:mainfrom
johntrandall:fix/active-user-count-keyerror

Conversation

@johntrandall
Copy link
Copy Markdown

Summary

  • Reddit's API no longer consistently includes active_user_count in subreddit responses
  • The current code uses d['active_user_count'] which raises KeyError when the field is absent
  • Changed to d.get('active_user_count') which returns None for missing keys, letting the existing ternary gracefully fall back to -1

Details

In redditwarp/models/subreddit.py line 215, the SubredditData.__init__ constructor accesses:

self.viewing_count: int = -1 if (x := d['active_user_count']) is None else x

When Reddit omits active_user_count from the API payload, this raises a KeyError. The fix uses .get():

self.viewing_count: int = -1 if (x := d.get('active_user_count')) is None else x

This is consistent with the existing intent — the code already handles None by defaulting to -1, so handling a missing key the same way is the natural extension.

Reddit removed the active_user_count field from some subreddit API
endpoints. The Subreddit model constructor used bracket access
(d['active_user_count']) which raises KeyError when the field is
absent. Changed to d.get('active_user_count') which returns None
for missing keys, falling through to the existing -1 default.

Added tests for Subreddit model construction covering:
- Complete API response (field present with value)
- Field present but None (search results)
- Field absent (new Reddit API behavior)
- Field present with zero value

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@johntrandall johntrandall force-pushed the fix/active-user-count-keyerror branch from 3b96dd0 to 092a3e2 Compare March 17, 2026 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant