tobymao / saq

Simple Async Queues
https://saq-py.readthedocs.io/en/latest/
MIT License
583 stars 41 forks source link

Context as kwarg #178

Closed magnus-kr closed 1 month ago

magnus-kr commented 1 month ago

If context were to be passed as a keyword argument instead of a positional one it would be easier to have functions that can be called regularly and also be queued.

For example:


async def get_pokemon_data(pokemon_name: str): 
    url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}" 
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        if response.status_code == 200:
            return response.json()
        else:
            return f"Error: {response.status_code}"

If I wanted to keep this function callable AND queueable currently, I'd have to modify the function like so:

async def get_pokemon_data(ctx: Context = None, pokemon_name: str = None):

The undesirable behavior here is having to set a default value for pokemon_name, because otherwise I'd get a syntax error: SyntaxError: non-default argument follows default argumentFlake8(E999)

If context was passed in as a kwarg, it could easily be modified to:

async def get_pokemon_data(pokemon_name: str, context: Context = None):

This makes even more sense if the function has a larger number of arguments

The only small drawback I see is that functions need to accept the same kwarg that it's being passed in by Worker.process:

task = asyncio.create_task(function(context=context, **(job.kwargs or {})))

tobymao commented 1 month ago

you can just pass in a null context, or wrap the function, this is too big of an api change