[Tutor] Proper way to use **kwargs?

Karjer Jdfjdf karper12345 at yahoo.com
Mon Mar 15 13:38:43 CET 2010


I want to use **kwargs to check a list of conditions (if true do this, if false do nothing) besides required parameters ( in sample a and b).  Sometimes I want to add a Python object (in example a dictionary and a list). Below is my first **kwargs-brew.

###START

def function_with_kwargs(a, b, **kwargs):
    options = {
        'logfile'   : None,
        'door'      : 'kitchendoor',
        'roof'      : 'tiles',
        'mydict'    : None,
        'mylist'    : None, }
    options.update(kwargs)

    logfile = options.get('logfile')
    if logfile == None:
        print "No logging"
    else:
        print "Logging"

    mydict = options.get('mydict')
    if mydict == None:
        print "Do nothing with dictionary"
    else:
        print "Do something with dictionary"

    mylist = options.get('mylist')
    if mylist == None:
        print "Do nothing with list"
    else:
        print "Do something with list"

    print "END OF FUNCTION\n"
        

somedict = { 'a': '1', 'b': '2', }
somelist = ['1', '2']

#DO SOMETHING
function_with_kwargs(1, 2, logfile='log.txt', door='frontdoor', mydict=somedict, mylist=somelist)

#DO NOTHING
function_with_kwargs(1, 2, door='frontdoor')



### END

I have 2 questions about this code:

1. Can I use this in Python 3 ?  I'm not sure if I can use **kwargs in Python 3 because it uses the "apply" builtin (if I understand it correctly)

"At this writing, both apply and the special call syntax described in this
section can be used freely in Python 2.5, but it seems likely that apply
may go away in Python 3.0. If you wish to future-proof your code, use
the equivalent special call syntax, not apply."

2. Are there better ways to achieve what I want to do?










      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100315/0bb33f09/attachment.html>


More information about the Tutor mailing list