Additional unpacking generalizations

One of the recent new features, introduced in Python 3.5, is the ability to extend the iterable (*) and dictionary (**) unpacking operators to allow unpacking in more positions, an arbitrary number of times, and in additional circumstances. I'll present you with an example concerning function calls:

# additional.unpacking.py
def additional(*args, **kwargs):
print(args)
print(kwargs)

args1 = (1, 2, 3)
args2 = [4, 5]
kwargs1 = dict(option1=10, option2=20)
kwargs2 = {'option3': 30}
additional(*args1, *args2, **kwargs1, **kwargs2)

In the previous example, we defined a simple function that prints its input arguments, args and kwargs. The new feature lies in the way we call this function. Notice how we can unpack multiple iterables and dictionaries, and they are correctly coalesced under args and kwargs. The reason why this feature is important is that it allows us not to have to merge args1 with args2, and kwargs1 with kwargs2 in the code. Running the code produces:

$ python additional.unpacking.py
(1, 2, 3, 4, 5)
{'option1': 10, 'option2': 20, 'option3': 30}

Please refer to PEP 448 (https://www.python.org/dev/peps/pep-0448/) to learn the full extent of this new feature and see further examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset