pythonkeyword-argument

How to use a single named parameter after *args


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.


Solution

  • I don't want kwargs, I thought that I can't just add port=xxxx in declaration parameters in my function while I have *args

    Python 3

    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))
    

    A more natural solution: using the **kwargs itself (Python 2 and 3)

    >>> 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')