Python Tricks : Function Argument Unpacking

简介: Python Tricks : Function Argument Unpacking

Python Tricks: Function Argument Unpacking
A really cool but slightly arcane feature is the ability to “unpack” funciton arguments from sequences and dictionaries with the and * operators.

Let’s define a simple funciton to work with as an example:

In [3]: def print_vector(x, y, z):
   ...:     print('<%s, %s, %s>' %(x, y, z))

As you can see, this function takes three arguments(x, y, and z) and prints them in a nicely formatted way. We might use this function to pretty-print 3-dimentional vectors in our program:

In [4]: print_vector(0, 1, 0)
<0, 1, 0>

Now depending on which data structure we choose to represent 3D vectors with, printing them with our print_vector function might feel a little awkward. For example, if our vectors are represented as tuples or lists we must explicitly specify the index for each component when printing them:

In [7]: print_vector(tuple_vec[0],
   ...:              tuple_vec[1],
   ...:              tuple_vec[2])
<1, 0, 1>

Using a normal function call with separate arguments seems unnecessarily verbose and cumbersome. Wouldn’t it be much nicer if we could just “explode” a vector object into its three components and pass everything to the print_vector function all at once?

(Of course, you could simply redefine print_vector so that it takes a single parameter representing a vector object–but for the sake of having a simple example, we’ll ignore that option for now.)

Thankfully, there’s a better way to handle this situation in Python with Function Argument Unpacking

In [8]: print_vector(*tuple_vec)
<1, 0, 1>

In [9]: print_vector(*list_vec)
<1, 0, 1>

Putting a * before an iterable in a function call will unpack

This technique works for any iterable, including generator expressions. Using the * operator on a generator consumes all elements from the generator and passes them to the function:

In [10]: genexpr = (x * x for x in range(3))

In [11]: print_vector(*genexpr)
<0, 1, 4>

Besides the operator for unpacking sequences like tuples, lists, and generators into positional arguments, there’s also the * operator for unpacking keyword arguments from dictionaries. Imagine our vector was represented as the following dict object:

In [12]: dict_vec = {
   'y': 0, 'z': 1, 'x':1}

We could pass this dict to print_vector in much the same way using the ** operator for unpacking:

In [13]: print_vector(**dict_vec)
<1, 0, 1>

Because dictionaries are unordered, this matches up dictionary values and function arguments based on the dictionary keys: the x argument receives the value associated with the ‘x’ key in the dictionary.

If you were to use the single asterisk(*) operator to unpack the dictionary, keys would be passed to the function in random order instead:

In [14]: print_vector(*dict_vec)
<y, z, x>

Python’s function argument unpacking feature gives you a lot of flexibility for free. Often this means you won’t have to implement a class for a data type needed by your program. As a result, using simple built-in data structures like tuples or lists will suffice and help reduce the complexity of your code.

相关文章
|
1月前
|
Linux Python
【Azure Function】Python Function部署到Azure后报错No module named '_cffi_backend'
ERROR: Error: No module named '_cffi_backend', Cannot find module. Please check the requirements.txt file for the missing module.
|
1月前
|
Java C++ Python
Python Function详解!
本文详细介绍了Python函数的概念及其重要性。函数是一组执行特定任务的代码,通过`def`关键字定义,能显著提升代码的可读性和重用性。Python函数分为内置函数和用户自定义函数两大类,支持多种参数类型,包括默认参数、关键字参数、位置参数及可变长度参数。文章通过多个实例展示了如何定义和调用函数,解释了匿名函数、递归函数以及文档字符串的使用方法。掌握Python函数有助于更好地组织和优化代码结构。
20 4
|
1月前
|
Go C++ Python
Python Tricks: String Conversion(Every Class Needs a ___repr__)
Python Tricks: String Conversion(Every Class Needs a ___repr__)
|
1月前
|
Go C# Python
Python Tricks:Python‘s Functions Are First-Class
Python Tricks:Python‘s Functions Are First-Class
|
1月前
|
前端开发 Python
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
|
1月前
|
C++ Python
Python Tricks--- Object Comparisons:“is” vs “==”
Python Tricks--- Object Comparisons:“is” vs “==”
|
1月前
|
Python
Python Tricks: Nothing to Return Here
Python Tricks: Nothing to Return Here
|
1月前
|
Python
Python Tricks : How to Write Debuggable Decorators
Python Tricks : How to Write Debuggable Decorators
|
1月前
|
Linux Go Python
Python Tricks :The Power Of Decorators
Python Tricks :The Power Of Decorators
|
1月前
|
安全 JavaScript 前端开发
Python Tricks: A Shocking Truth About String Formatting(二)
Python Tricks: A Shocking Truth About String Formatting(二)
下一篇
无影云桌面