Python function arguments (object, Keys, Default)

Python function arguments(objects, Keywords, Default, Tuples,)

Python function arguments

Arguments

The arguments specified in a function definition are taken in the order in which they are defined, for example:

def message to, text):
      print "This is a message for",to, ":\n", text 
message (Martin', 'Your dinner is ready!")

Arguments are passed to the function by assignment; the normal rules of assignment apply to the arguments contained in a function definition. The argument-passing process therefore follows these rules:

1. Arguments are copied by reference into locally scoped objects. This means that the variables used to access function arguments are not related to the objects supplied to the function. This also means that changing a local object does not modify the original argument.

2. Mutable objects can be changed in place. When you copy a list or dictionary. you copy a list of object references. If you change the value of a reference, you modify the original argument.

The first rule means that you can safely use the local versions of an object without worrying about modifying the original. For example, the code

def modifier (number, string, list):
      number =5
      string=  'Goodbye'
      list = [4,5,6]
      print "Inside", number, string, list

Number =1
String ='Hello'
List = [1,2,3]

Print "Before", number, string, list
modifier (number, string, list)
Print "After:", number, string, list

Generates the following output :

Before: 1 Hello [1,2,3]
Inside: 5 Goodbye [4,5,6]
After: 1 Hello [1,2,3]

The local versions of number, string, and list have been modified, but the original still retain their original values.

The second rule says that any mutable object can be modified in place. This allows us to change the information pointed to by a specific element of a mutable list or dictionary. Consider the following example:

def modifier (list):
       List [0:3] = [4,5,6]
       Print "Inside:", list
List = [1,2,3]

Print "before", list
Modifier "After:" , list

This code generates the following output when excecuted:

Before : [1,2,3,]
Inside : [4, 5, 6 ]
After : [4, 5, 6]

To copy the list dictionary object of copying it’s reference, you must explicitly do a copy. The next example instead the following line as the first line in the modifier function:

List = list [:]

Executing the script, you get

Before : [1, 2, 3]
Inside : [4, 5, 6,]
After : [1, 2, 3]

Arguments Are objects

Although this may seem obvious now, arguments are just names for object-the underlying type of the object in question remains the same. Also, because an argument is just a pointer, the type of the object passed does not need to be defined. The example

Def multiply (x, y):
       Return x * y

When run on numerical objects, returns a number:

>>> multiply (2,3)
6

Or it could return a string:

>>>multiply ('Ha' ,5)
'HaHaHaHaHa'

Or it could return a list :

>>> multiply ([1, 2, 3],5)
[ 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

However, be aware that object types that are not number sequences will raise an exception, because the types are incompatible (see Chapter 7 on exceptions). By using objects rather than strict variable types, you can create individual functions that appear to do a number of different things just by accepting different types of objects as arguments.

Argument Calling by Keywords

Beyond the normal sequence of argument calling, where each argument is assigned in order to the function’s argument definition, Python also supports a number of other function/argument-calling formats. The problem with the traditional sequence assignment is that it is limited to accepting a specific number of arguments in a specific sequence. For readability, this technique is not always practical, and it’s useful to have some flexibility when supplying information to a function if it can be made to do a number of different things other than the traditional single-purpose function supported by C, C++, or Visual Basic.

The most basic extension beyond sequence assignment is the ability to specify arguments by keyword assignment. For example, you could have called the multiply function like this:

multiply(x=5, y=10)

In this case, the order of the arguments is not important so you can also do this:

multiply( y = 10 ,x-5)

Default Arguments

Within the function definition, Python allows you to specify the default values for each argument. Normally, you must supply the same number of arguments as defined by the function definition. Using defaults, you can call a function and omit arguments and the function will still execute. The format for defining default values is

def function( ARG = VALUE)

where VALUE is the default to be applied to the argument if it is not supplied.

For example, let’s create a function that calculates the volume of a cone. The function definition looks like this:

def cone_volume (height, radius=1, pi=3.141592654: ):
      cone = (1.0) / (3.0) * height* pi* pow(radius,2)
return cone

Now you can call this function in any of the following ways:

cone_volume (4,3,(22.0/7.0))
cone_volume (4,3)
cone volume (4)
cone_volume (radius=3, height = 4 )
cone_volume(pi = (22.0/7.0),
                        radius=4,
                        height=4)

Note that you cannot omit the height value that argument does not have a default value and consequently, Python treats it as a required value. Also note that default values should ideally be the last arguments in the definition, although the following definition will work:

def cone_.volume(radius-1,pi=3.141592654,height):

If you call the function with only one argument, the compiler will raise an exception because Python cannot decide to which argument the supplied value should be applied:

>>> cone_volume (4)
Traceback (innermost last):
File "<stdin>", line 1, in?
File "<stdin>", line 2, in cone_volume
TypeError: number coercion failed

Note:- You get a TypeError exception here because the height argument is passed a value of Nome. This is implied because you haven’t supplied enough zahues. When Python attempts the calculation, it tries to convert the value supplied to a number, but of course None is not a value that can be converted, so have you have a type mismatch.

Argument Tuples

For accepting a variable length of arguments when you don’t want to use default values, you can use the argument tuple:

der function(*ARG)

All the arguments are placed into the tuple specified by ARG. For example, the following function accepts a variable list of arguments that are appended to the list defined in the first argument:

def multi_insert(list, *items):
      for item in list:
      list.append(item)

Argument tuples pick up all the remaining nonpositional arguments in a function call. As such, they should be specified last. It should also be obvious that you can only have one argument tuple in a function definition.

Argument Dictionaries

Argument dictionaries work in a similar way to keyword argument passing except that instead of assigning values to individual variables, each keyword/value pair creates an entry in the specified dictionary

def function (**ARG):

For example, the function

def message(text, **header):
for field in data.keys():
      print field"1",data[field]
print
print text

can be called to create a standard email message:

message ('I pulled the chain but nothing happened!',
From= 'mc@mcwords.com',
To= 'mc@mcwords.com',
Subject=('Hello)

When called, this function generates the following output:

Subject: Hello
To : mc@mcwords.com
From: mc@mcwords.com
I pulled the chain but nothing happened!

Like Tuple argument, a dictionary arguments must be last, following any sequential or default argumenta. You can also combine a tuple and dictionary arguments , as in the midfield version of the message function:

def message (text, *lines, **header):
    For field in header. Keys ():
       Print field+":", header [field]
Print
Print text
For line in lines:
     Print line

Message ('I pulled the chain but nothing happened!',
  'Another line',
  'Second line',
From= 'mc@mcwords.com',
To= 'mc@mcwords.com',
Subject= 'Hello')

When called, this function creates a multiline e-mail message:

Subject : Hello
To : mc@mcwords.com
From: mc@mcwords.com

I pulled the chain but nothing happened!
Another line
Second line

Function Rules

Python has strict rules about how it parses function calls and definitions. Python follows these rules when you are defining the function:

•Defaults must follow nondefault arguments.
•you can only have one tuple argument (*arg) and one dictionary argument (**arg)
Within a single definition.
•The tuple argument (*arg) must appear after sequential arguments and defaults.
•The dictionary argument must appear last.

When calling a function, Python follows these rules:

•Function calls must include parentheses, func and func() are not the same. The
first accesses the function reference, and the second executes the function.

•Keyword arguments must appear after all the nonkeyword arguments.

In addition, Python tries the following steps in order, when determining the arguments to be assigned within the function:

â– Assign nonkeyword arguments by sequence.

â– Assign keyword arguments by argument name.
â– Assign extra nonkeyword arguments to the argument tuple.

â– Assign extra keyword arguments to the argument dictionary.
â– Assign default values to any unassigned arguments.

Return Values

The return statement returns the objects specified to the calling program. The basic format is:

return OBJECT [, OBJECT,  ....]

The return statement is not limited to returning single objects; it can return tuples, lists, or dictionaries. The tuple is probably the most useful, because it allows you to assign multiple objects to the returned value.

For example, here’s a transform function that accepts two arguments and returns the first argument squared and the second argument cubed:

def sqsq(first, second):
       first =first*first
      Second = second**3

You can now call the sqsq function and immediately get the results:

squared, cubed = sqsq  (2,3)

See the discussion on “Tuple and List Assignments” in Chapter 3 for more information.

Advanced Function Calling

Beyond the basics of functions that you’ve already seen, Python also supports some advanced function handling. The apply statement is a required feature if you want to be able to dynamically call a function without knowing beforehand its name or the arguments you need to supply it. The map statement provides the same functionality as the Perl map function, it allows you to apply the same function to an arbitrary list.

The last two features are connected. It should come as no surprise that functions are just Python objects. As such, you can assign functions to names and then call them dynamically and therefore indirectly. As an extension of this, you can also create a name that points to a function that has no real name-an anonymous function that is created within Python using the lambda statement.

The apply Statement

There are times when you want to be able to call a function within an application, but you don’t know the name of the function or the number of arguments that you need to supply to the function. The apply function allows you to apply a number of arguments to a function, executing the function as if you were calling it explicitly. The format of an apply statement is:

apply(FUNCTION, TUPLE)

Here’s an example of calling the apply function:

apply(multiple,(2,4))

The big benefit here is that because the arguments are supplied as a tuple and therefore as a data structure, the function call can be computed at run time, instead of at development time. You’ll see examples of the apply statement throughout this book.

The map Statement

Imagine that you have a list of numbers and you want to turn it into a list of cubes. The normal process might be:

for index in range(len(list)):  
      list[index] = pow(list[index],3)

For this simple function it makes sense, but for complex functions, having to manually embed the function call on each item in a list within a loop creates unnecessary overhead.
A simpler method is to use the map statement. The map statement accepts the name of a function and a list or tuple on which to act. You can therefore rewrite the preceding code fragment as

def cube(x):
  return pow(x, 3)
  map(cube, list)

Although it doesn’t look any shorter, it is much more practical. The map function does the loop operation and reassignment for you, and you can supply any function as the first argument to the map statement. More often, the map statement is used in combination with the lambda statement, which creates anonymous functions, allowing you to rewrite the preceding statements as

Map(lambda x:pow(x:3), list)

You’ll learn about the creation of anonymous functions later in this chapter, see “Anonymous Functions for more details.
These two formats, calling a named function and using an anonymous function, are syntactically similar to the expression and block formats used by Perl. The Perl statement

map EXPR, LIST

is roughly equivalent to the Python statement

map (FUNC, LIST)

while the Perl statement

map BLOCK LIST

is roughly equivalent to the Python statement

map(lambda ARG: EXPRESSION, LISTY)

Indirect Function Calls

Functions are just Python objects, which means they can be assigned to names and passed to other functions just like any other object. For example, you can create an alias to a function as in the following example:

def hello():
       print "Hello world"
x=hello
x()

Note the notation used in the preceding example. You assign the hello object to the x name. By specifying the function by its object reference, hello, instead of calling it as a function, hello(), you copy the reference to the function instead of executing it and assigning the result.
This use of function references also means you can supply a function object as an argument to a function:

def call(function,* args):
       function(args)
call (multiply,2,2)

Finally, using the same methods, you can also place function objects inside other data structures:

obj_dict = { 'function' : multiply, 'args' : (2,2)}
apply (obj_dict [ 'function' ], obj_dict ['args'])

Note in the preceding example the use of apply, which accepts the first argument as a function reference and accepts the tuple as the arguments to be supplied to the function.

Anonymous Functions

Anonymous functions are a vital component of the flexibility offered by languages such as Perl and Python. You’ve already seen a few examples of anonymous functions within Python. In C/C++ the closest approximation to an anonymous function is the inline function feature, you can define a block or expression to be executed just as if it was a real function call, but without the overhead associated with predeclaring a typical function.

The format for creating an anonymous function in Python is to use the lambda expression. Because lambda is an expression, not a statement, you can call lambda in places where a typical def statement could not be used. In addition, the lambda expression returns a function object without giving it a name. The returned object can then be used just like an indirect function call.

The general format for the lambda expression is

lambda ARG [, ARG, ...]: EXPR

The ARG is an argument, just like a typical def statement. The arguments work just like sequential arguments in a normal function. You can also use defaults within a lambda definition, but you cannot use any other argument feature.
The EXPR is a single-line expression that is executed when the function is called.

When creating and using lambda functions, you need to remember the following important differences from ordinary functions:

1. Functions created by lambda only accept a single expression-you cannot have multiline anonymous functions.

2. The result of the expression in a lambda function is always returned to
the caller.

For example, you can use lambda to create an anonymous function that cubes a number and then assigns the result to a name:

f =  lambda x: x*x*x

f(2)

The preceding statement is actually how a typical def statement works, the difference is that the assignment to a name is automatic.

Compared to Perl, the use of the lambda expression is identical to the sub anonymous function statement; Python has just given the process a separate name instead of combining the operation into a single statement. In essence, the lambda expression is no different than the def statement.

The lambda function is used in a large number of areas such as sorting and as inline functions when creating user interfaces. You’ll see more examples of this as you work through the book.

Previous articlePalindrome Program in Java in Hindi
Next articlePython is an object-oriented programming language