Back to Blog
Python function6/17/2023 Perhaps unnecessary to say: this decorator can be re-used for other functions too. Next, it executes the actual function and returns its result as if the function was called regularly. This function prints the argument and the name of the called function. Inside print_argument, we define a wrapper function. Print("Argument for", func._name_, "is", the_number) Let’s create our own decorator it’s simpler than you might expect and might come in handy someday: def print_argument(func): There are many use-cases for decorators, and you may have used them before when working with frameworks like Flask. Similarly, we can use a single * to unpack a list and feed its content as positional arguments to a function: > def f(a, b, c):ĭecorators are wrappers around a function that modify the behavior of the function in a certain way. You can unpack a dictionary for use with named keywords by using the ** prefix: > def f(a, b): It will generally make your code more readable. In such cases, the second-best option is to create a dictionary with all the named arguments and pass that to the function instead. Although this should be avoided altogether, for example, by using data classes, it’s not always up to you. Some functions require a long list of arguments. In such cases, this is the way to force users of your library to use named arguments, making the order irrelevant. Perhaps you don’t want to commit to a certain order of arguments (yet). This advanced function trick could come in handy when you’re developing some kind of library. ![]() Or, as shown below, before everything, forcing all arguments to be keyword arguments: > def f(*, a, b): The details are described in PEP 3202, but it comes down to using an asterisk before the arguments you want to force as keyword arguments. What you might not know is that you can also force keyword arguments. That’s nice, but you probably already knew these things. Without looking up the function itself, you can often guess what the argument is used for by looking at the names. ![]() You’re not forced to a particular order in which you supply your arguments-the name matters, not the position.Keyword arguments have a number of advantages: 2 Using * and ** for function arguments.
0 Comments
Read More
Leave a Reply. |