Detailed description of default parameters in Python functions

Source: Internet
Author: User
Import datetime as dt def log_time (message, Time=none):  If Time is None:    time=dt.datetime.now ()  print ("{0}: {1} ". Format (Time.isoformat (), message))

Recently I found in a python code a very nasty bug that was caused by the wrong use of default parameters. If you already know all about the default parameters and just want to laugh at my ridiculous mistake, skip to the end of this article. Hey, I wrote this code, but I'm pretty sure I was possessed by the demon that day. You know, sometimes that's the way it is.

This article simply summarizes some basic elements of the standard parameters and default parameters for Python functions. Alert you to the pitfalls that may exist in your code. If you're just beginning to touch Python and start writing some functions, I really recommend that you look at the contents of the function in the official Python manual, with the following links: defining Functions and more on defining Functions.
Simply review the function

Python is a powerful object-oriented language that pushes this programming paradigm to its zenith. However, object-oriented programming still relies on the concept of functions, which you can use to process data. Python has a broader concept of callable objects, that is, any object can be called, which means that the data is applied to it.

A function is a callable object in Python, and at first glance it behaves similarly to functions in other languages. They fetch some data, called parameters, and then process them, then return the result (none if no return statement)

Parameters are declared as placeholders (when defining a function) to represent those objects that are actually passed in when the function is called. In Python you don't need to declare the type of the parameter (for example, as you did in C or Java) because the Python philosophy relies on polymorphism.

Remember that the Python variable is a reference, that is, the memory address of the actual variable. This means that Python's functions will always work in a "pass-through" mode (a C + + term is used here), and when you invoke a function, instead of copying the value of a parameter to replace the placeholder, the placeholder points to the variable itself. This leads to a very important result: you can change the value of the variable within the function. Here is a good visual explanation of the reference mechanism.

References play a very important role in Python, which is the backbone of a fully polymorphic python approach. For this very important topic, please click on this link to see a better explanation.

To check if you understand this basic feature of the language, follow this simple code (the variable ph stands for "placeholder (placeholder)")

>>> def print_id (ph): ... print (Hex (ID (ph))) ...>>> a = 5>>> print (Hex (ID (a))) 0x84ab460> >> print_id (a) 0x84ab460>>>>>> def alter_value (ph): ... ph = ph + 1 ... return ph ... >>> B = Alter_value (a) >>> b6>>> a5>>> Hex (ID (a)) ' 0x84ab460 ' >>> hex (ID (b) ) ' 0x84ab470 ' >>>>>> def alter_value (ph): ... ph.append (1) ... return ph ... >>> a = [1,2,3]>>> B = Alter_value (a) >>> a[1, 2, 3, 1]>>> b[1, 2, 3, 1]>>> he X (ID (a)) ' 0xb701f72c ' >>> hex (ID (b)) ' 0xb701f72c ' >>>

If you're not surprised by what's happening here, it means you've mastered one of the most important parts of Python, and you can safely skip the explanations below.

The print_id () function shows that the placeholders inside the function are exactly the same as the variables passed in at run time (their memory addresses are identical).

Two versions of Alter_value () are intended to change the value of the passed-in parameter. As you can see, the first alter_value () does not change the value of variable A as successfully as the second Alter_value (). What is this for? In fact, both behave the same way, trying to modify the value of the original variable passed in, but in Python, some variables are immutable (immutable), and integers are in this column. On the other hand, the list is not immutable, so the function is able to perform the work guaranteed by its name. Here you can find a more detailed introduction to the immutable types.

There are some things to say about functions in Python, but these are the basics of standard parameters.
Default parameter values

Sometimes you need to define a function that allows it to accept a parameter, and the function behaves differently when the parameter appears or does not appear. If a language does not support this situation, you have only two choices: the first is to define two different functions, decide which one to invoke for each invocation, and the second, both of which are feasible, but are not optimal.

Python, like other languages, supports default parameter values, that is, the function parameter can be specified at the time of invocation, or it can be left blank to automatically accept a pre-defined value.

A very simple (and useless) example of the default value is as follows:

def log (Message=none):  if message:    print ("log: {0}". Format (Message))

This function can run with one parameter (can be none)

>>> log ("File closed") log:file closed>>> log (None) >>>

But it can also run without parameters, in which case it will accept the default values set in a function prototype (none in this case)

>>> log () >>>

You can find more interesting examples in the standard library, such as in the Open () function (see official documentation)

Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)

A function prototype can prove, for example, that a call such as F = open ('/etc/hosts ') hides many parameters (mode, buffering, encoding, etc.) by passing in the default values, and makes the typical application case of this function very easy to use.

As you see in the built-in open () function, we can use either standard or default arguments in the function, but the order in which they appear in the function is fixed: the standard parameters are called first, and then the default parameters are called.

Def a_rich_function (A, B, C, D=none, e=0):  Pass

The reason is obvious: if we can put a default parameter in front of the standard parameter, the language will not understand, the default parameter has been initialized. For example, consider the following function definition

Def a_rich_function (A, B, D=none, C, e=0):  Pass

What parameters do we pass when the function a_rich_function (1, 2, 4, 5) is called? is d=4, c=5 or c=4, e=5? Because D has a default value. So the definition of this order is forbidden, and if you do, Python throws a SyntaxError

>>> def a_rich_function (A, B, D=none, C, e=0): ... pass ... File "
 
  
   
  ", line 1syntaxerror:non-default argument follows default Argument>>>
 
  

Default parameter evaluation

The default parameters can be improved by either a normal value or a function call result, but the latter technique requires a special warning

A normal value is hard-coded, so other than when compiling, the value is not required at other times, but the function call expects to perform the evaluation at run time. So we can write that.

Import datetime as dt def log_time (message, Time=dt.datetime.now ()):  print ("{0}: {1}". Format (Time.isoformat (), Message))

Every time we call Log_time () We expect it to provide the current time correctly. The tragedy is not successful: the default parameter is evaluated when it is defined (for example, when you first import the module), the result of the call is as follows

>>> log_time ("message 1") 2015-02-10t21:20:32.998647:message 1>>> log_time ("Message 2") 2015-02-10t21:20:32.998647:message 2>>> log_time ("Message 3") 2015-02-10t21:20:32.998647:message 3

If you assign a default value to an instance of a class, the result is even more bizarre, and you can read about it in Hitchhiker's Guide to python!. Under.. The usual workaround is to replace the default parameter with none, and check the parameter values inside the function.

Conclusion

The default parameter can greatly simplify the API, you need to pay attention to its unique "point of failure", that is, the time to evaluate the value. Surprisingly, one of the most basic things about Python, parameters and references to functions, is one of the biggest sources of error, and sometimes for experienced programmers as well. I suggest taking the time to learn about citations and polymorphism.
Related reading:

    • OOP Concepts in Python 2.x–part 2
    • Python 3 OOP part 1–objects and types
    • Digging up Django class-based views–2
    • Python Generators–from iterators to cooperative multitasking–2
    • OOP Concepts in Python 2.x–part 1
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.