How can I use single **kwargs
in my program? I need it to set a port number in an application uses sockets. I have to use **kwargs
because I use *args
as well so I can't just add port=xxxx
in my function arguments.
def myFunction(*args, **kwargs):
...
socket.connect(("xx.xx.xx.xx", kwargs.values()))
...
myFunction("something", "other", port = xxxx)
I'm now using kwargs.values()
to set the port number, but it isn't good idea I think.
I don't want
kwargs
, I thought that I can't just addport=xxxx
in declaration parameters in my function while I have*args
In Python 3 it's possible to define a paramter after *args
:
>>> def func(*args, port):
... print(port)
... print(args)
...
>>> func('something', 'args', port='8000')
8000
('something', 'args')
However this will generate a syntax error in Python 2.
To adapt this to your code you can use:
#python3 only
def func(*args, port):
socket.connect(('xx.xx.xx.xx', port))
>>> def func(*args, **kwargs):
... print(args)
... print(kwargs)
...
>>> func('something', 'other', port='8000')
('something', 'other')
{'port': '8000'}
As you can see, you can pull the port
parameter if it is provided, in the kwargs
dict
def func(*args, **kwargs):
socket.connect(('xx.xx.xx.xx', kwargs['port']))
If you want to have a default value like @wovano suggested :
def func(*args, **kwargs):
socket.connect(('xx.xx.xx.xx', kwargs.get('port', default_port)))
Call it using:
func('something', 'other', port='8000')
Or using the default port value:
func('something', 'other')