2. Unpacking return elements

2.1. * and ** operators

  • This is not multiplication and power
  • * zwykle nazywa się *args (arguments) - argumenty pozycyjne (anonimowe)
  • ** zwykle nazywa się **kwargs (keyword arguments) - argumenty nazwane
  • *args unpack tuple or list
  • **kwargs unpack dict

2.2. Unpacking values from function

2.2.1. Recap of assignment information

line = '4.9,3.1,1.5,0.1,setosa'

line.split(',')
# ['4.9', '3.1', '1.5', '0.1', 'setosa']
line = '4.9,3.1,1.5,0.1,setosa'

sepal_length, sepal_width, petal_length, petal_width, species = line.split(',')

sepal_length    # '4.9'
sepal_width     # '3.1'
petal_length    # '1.5'
petal_width     # '0.1'
species         # 'setosa'

2.2.2. Unpacking values at the right side

line = '4.9,3.1,1.5,0.1,setosa'

sepal_length, sepal_width, *others = line.split(',')

sepal_length    # '4.9'
sepal_width     # '3.1'
others          # ['1.5', '0.1', 'setosa']

2.2.3. Unpacking values at the left side

line = '4.9,3.1,1.5,0.1,setosa'

*features, species = line.split(',')

features        # ['4.9', '3.1', '1.5', '0.1']
species         # 'setosa'

2.2.4. Cannot unpack from both sides at once

line = '4.9,3.1,1.5,0.1,setosa'

*a, b, *c = line.split(',')
# SyntaxError: two starred expressions in assignment

2.2.5. Naming convention

  • if you’re not using features later in your code
line = '4.9,3.1,1.5,0.1,setosa'

*_, species = line.split(',')

2.3. Example

def get_iris():
    """
    Would be nice, if you can get ``dict``...
    but most programmers will return ``tuple``
    because it's a bit faster

    return {
        'sepal_length': 4.9,
        'sepal_width': 3.1,
        'petal_length': 1.5,
        'petal_width': 0.1,
        'species': 'setosa'
    }
    """
    return 4.9, 3.1, 1.5, 0.1, 'setosa'

*features, species = get_iris()

2.4. Assignments

2.4.1. Hosts

  • Filename: kwargs_hosts.py
  • Lines of code to write: 15 lines
  • Estimated time of completion: 15 min
  • Input data: Code Listing 2.1.
  1. Skopiuj zawartość listingu poniżej do pliku hosts.txt
  2. Stwórz pusty dict o nazwie hosts
  3. Czytając plik pomiń puste linie lub zaczynające się od komentarza #
  4. Do hosts dla klucza IP dodaj listę hostname
  5. Przy parsowaniu linii skorzystaj z konstrukcji z gwiazdką *
Code Listing 2.1. Listing pliku /etc/hosts
##
# ``/etc/hosts`` structure:
#   - IPv4 or IPv6
#   - Hostnames
##

127.0.0.1       localhost
127.0.0.1       astromatt
10.13.37.1      nasa.gov esa.int roscosmos.ru
255.255.255.255 broadcasthost
::1             localhost