Skip to content

Add support for next(cursor) - #1064

Merged
dvarrazzo merged 1 commit into
masterfrom
cursor-next
May 4, 2025
Merged

Add support for next(cursor)#1064
dvarrazzo merged 1 commit into
masterfrom
cursor-next

Conversation

@dvarrazzo

Copy link
Copy Markdown
Member

This MR transforms the cursor from an iterable (supporting iter()) to an iterator (supporting iter() and next()).

next(cursor) behaves like cursor.fetchone(), but its result is Row, not Row | None. That's because, if there is no row to fetch, it will raise StopIteration.

This makes simpler to write strictly typed code using the result when there is a 100% guarantee that a query will return a record (or will raise an exception), for example when fetching count(*), which always returns a result even if the counted records are 0. The type checker is not aware of that, therefore you need to guard for None with an if, or an assert, or you need to do something horrible like (rec,) = cur.fetchall() in order to convince Mypy that rec will never be none.

@dlax dlax left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very useful addition!!

@dvarrazzo dvarrazzo added this to the 3.3 milestone May 4, 2025
@dvarrazzo
dvarrazzo force-pushed the cursor-next branch 3 times, most recently from dee18f7 to daf36ab Compare May 4, 2025 18:55
This allows to call `next(cursor)`, which is guaranteed to never return
None, making type checking simpler.
@dvarrazzo
dvarrazzo merged commit 4ab4c02 into master May 4, 2025
@dvarrazzo
dvarrazzo deleted the cursor-next branch May 4, 2025 21:33
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.

2 participants