Python functions with arbitrary arguments

A function can be defined in Python with arbitrary number of arguments by prefixing one of the argument with *. e.g. you may have an addition function that sums at least two numbers but user is more than welcome to pass in more arguments. The function would look something like this:

def addition(a, b, *args):
    sum = a+b
    if args:
        for arg in args:
            sum += arg
    return sum

print addition(1,2)  #Will output 3
print addition(1,2,3,4)  #Will output 10

Similarly, you could pass arbitrary number of key-value pairs to a function. e.g. you may have an email function where you would require to pass the to, from, subject and body. The cc and bcc parameters could be optional. You could define a function like this:

def mail(to, subject, body, **kwargs):
    print to
    print subject
    print body
    if kwargs:
        if 'cc' in kwargs:
            print 'Add cc to email'
        if 'bcc' in kwargs:
            print 'Add bcc to email'

mail('to@domain.com', 'Testing', 'Email body') 
#Will send email to recipient with subject and body
mail('to@domain.com', 'Testing', 'Email body', cc='cc@domain.com', bcc='bcc@domain.com')
#Will send email to recipient with subject, body and also cc and bcc recipients
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s