Pass an additional argument to a function

Hi,

I try to get asyncio.start_unix_server working.

it seem that this function accept additional args *

those arguments will be passed to client_connected_cb callback ? or how can I pass additional args to this callback ? Thanks.

According to the docs:

The client_connected_cb callback is called whenever a new client connection is established. It receives a (reader, writer) pair as two arguments, instances of the StreamReader and StreamWriter classes.

So its cannot take any additional arguments.

But you can parameterize your callback using a closure or the functools.partial tool.

For example:

import asyncio

[...]

def _make_my_callback(my_custom_arg):
    async def my_callback(reader, writer):
        print(f"{reader=}, {writer=}, {my_custom_arg=}")
        [...]
    return my_callback

[...]

async def main():
    client_connected_cb = _make_my_callback(my_custom_arg=[42])
    server = await asyncio.start_unix_server(client_connected_cb, "/my/unix/socket/path")
    [...]

Or:

import asyncio
import functools

[...]

async def my_callback(reader, writer, *, my_custom_arg):
    print(f"{reader=}, {writer=}, {my_custom_arg=}")
    [...]

[...]

async def main():
    client_connected_cb = functools.partial(my_callback, my_custom_arg=[42])
    server = await asyncio.start_unix_server(client_connected_cb, "/my/unix/socket/path")
    [...]

(warning: not tested)

1 Like

It does not accept additional args. See Keyword-Only Arguments

1 Like

Because how the start_unix_server() function’s parameters are defined in its source code, it may look like it accepts additional keyword-only arguments, but it actually doesn’t. That is, it only accepts the arguments specified in its docs (and most of them are passed to the event loop’s method create_unix_server()).

1 Like

Thank you @zuo @elis.byberi