简体   繁体   中英

Mixing default arguments in Python 2.x

I'm trying to mix default keyword arguments, positional arguments and keyword arguments in Python 2.7. From the following code, I expect profile=='system' , args==(1,2,3) and kwargs={testmode: True} .

def bla(profile='system', *args, **kwargs):
    print 'profile', profile
    print 'args', args
    print 'kwargs', kwargs


bla(1, 2, 3, testmode=True)

What I get is:

profile 1
args (2, 3)
kwargs {'testmode': True}

Can this be done in Python 2.7 or do I need Python 3.x?

In Python2:

def bla(*args, **kwargs):
    profile = kwargs.pop('profile', 'system')
    print 'profile', profile
    print 'args', args
    print 'kwargs', kwargs

In Python3 it's possible to define keyword-only arguments :

def bla(*args, profile='system', **kwargs):
    print('profile', profile)
    print('args', args)
    print('kwargs', kwargs)

the call bla(1, 2, 3, testmode=True) yields

profile system
args (1, 2, 3)
kwargs {'testmode': True}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM