[Python] Reason of avoiding recursive function calling

Avoiding Recursion in Game Search Logic

How did I encounter this?

While working on the game search functionality, it became clear that the structure of the search logic influenced the need for recursion. Initially, the search was divided into two separate loops—one for searching in gameDB and another for searching in Wikidata. This led to a problem where the function needed to call itself recursively in order to ensure a complete search process.

The Original Structure

The original approach had two independent loops.

while game_db_search_count < 3:
    # Search in gameDB
while wikidata_search_count < 3:
    # Search in Wikidata

If the game was not found in the database, the system moved on to search Wikidata. If Wikidata returned results, the game was added to gameDB, but there was no direct way to return to the database search process. As a result, the function had to call itself recursively.

if game_not_found:
    await resolve_game_entry(search_title, db_connection_pool, 10, 0)

Why This Approach Was Reconsidered

  1. Recursion introduces unnecessary function calls

    • Each recursive call adds another layer to the call stack, even though the logic could be handled iteratively.
    • If an unexpected issue occurs, excessive recursion could lead to performance issues.
  2. A single loop simplifies the process

    • Instead of separating gameDB and Wikidata searches, combining them into a single loop makes it easier to retry the database search after inserting a game.
  3. Easier to control retries and prevent unnecessary searches

    • With recursion, the function could be called multiple times unnecessarily.
    • A loop ensures that the process only repeats when needed.

A More Practical Approach

Instead of using recursion, the function was restructured to use a single loop.

while attempts < 2:
    if not game_found:
        # Search in gameDB
    if game_not_found and attempts == 0:
        # Search in Wikidata
        # If found, insert into gameDB
    attempts += 1

This ensures that the database is always checked first, then Wikidata, and finally the database is checked again after any new game entries have been added. By keeping everything within a single loop, the need for recursion is eliminated while maintaining the intended behavior.

Comments