I am reusing a piece of code from another developer (it is a socket listener) which has the following function:
def start_my_client(self, *, config: dict):
I am new to Python, so I am assuming it requires a dictionary variable to be passed as an argument, so I created this variable:
config_dic = {'name': 'my_socket', 'hostname': 'test', 'description': 'TEST'}
However, I tried many different ways to pass the variable when calling the function, but none of them worked for me, for example:
def handle_messages(conn, addr):
conn.start_my_client(config=config_dic)
I receive nothing from the function. I tried this too:
def handle_messages(conn, addr):
conn.start_my_client(**config_dic)
It throws this error:
TypeError: start_my_client() got an unexpected keyword argument 'name'
Any hint on how to pass the variable?
CodePudding user response:
The first call looks reasonable
def handle_messages(conn, addr):
conn.start_my_client(config=config_dic)
What is expected output for this?
If you pass config_dic like that
def handle_messages(conn, addr):
conn.start_my_client(**config_dic)
you perform unpacking arguments here. This means that the method start_my_client get arguments the same way as if you would call method like that
conn.start_my_client(name='my_socket', hostname='test', description='TEST')
This is the reason you got error
TypeError: start_my_client() got an unexpected keyword argument 'name'
start_my_client doesnt expect argument called name.
CodePudding user response:
As mentioned in:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
the function you are using can receive several different arguments:
def start_my_client(self, *, config: dict):
So, it could take a number of arguments when called, something like this:
conn.start_my_client(a, b, c)
As for the :
, this
Just indicate that each of the parameters passed should be dicts
.
So, you could just call the function as:
def handle_messages(conn, addr):
conn.start_my_client(config_dic)