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.

相关文章
|
7月前
|
Python
[oeasy]python086方法_method_函数_function_区别
本文详细解析了Python中方法(method)与函数(function)的区别。通过回顾列表操作如`append`,以及随机模块的使用,介绍了方法作为类的成员需要通过实例调用的特点。对比内建函数如`print`和`input`,它们无需对象即可直接调用。总结指出方法需基于对象调用且包含`self`参数,而函数独立存在无需`self`。最后提供了学习资源链接,方便进一步探索。
184 17
|
7月前
|
人工智能 Python
[oeasy]python083_类_对象_成员方法_method_函数_function_isinstance
本文介绍了Python中类、对象、成员方法及函数的概念。通过超市商品分类的例子,形象地解释了“类型”的概念,如整型(int)和字符串(str)是两种不同的数据类型。整型对象支持数字求和,字符串对象支持拼接。使用`isinstance`函数可以判断对象是否属于特定类型,例如判断变量是否为整型。此外,还探讨了面向对象编程(OOP)与面向过程编程的区别,并简要介绍了`type`和`help`函数的用法。最后总结指出,不同类型的对象有不同的运算和方法,如字符串有`find`和`index`方法,而整型没有。更多内容可参考文末提供的蓝桥、GitHub和Gitee链接。
196 11
|
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.
256 2
|
Go C++ Python
Python Tricks: String Conversion(Every Class Needs a ___repr__)
Python Tricks: String Conversion(Every Class Needs a ___repr__)
127 5
|
Java C++ Python
Python Function详解!
本文详细介绍了Python函数的概念及其重要性。函数是一组执行特定任务的代码,通过`def`关键字定义,能显著提升代码的可读性和重用性。Python函数分为内置函数和用户自定义函数两大类,支持多种参数类型,包括默认参数、关键字参数、位置参数及可变长度参数。文章通过多个实例展示了如何定义和调用函数,解释了匿名函数、递归函数以及文档字符串的使用方法。掌握Python函数有助于更好地组织和优化代码结构。
378 4
|
Go C# Python
Python Tricks:Python‘s Functions Are First-Class
Python Tricks:Python‘s Functions Are First-Class
123 3
|
前端开发 Python
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
85 1
|
C++ Python
Python Tricks--- Object Comparisons:“is” vs “==”
Python Tricks--- Object Comparisons:“is” vs “==”
105 1
|
Python
Python Tricks: Nothing to Return Here
Python Tricks: Nothing to Return Here
91 1
|
Python
Python Tricks : How to Write Debuggable Decorators
Python Tricks : How to Write Debuggable Decorators
71 1

推荐镜像

更多