Side effects en funciones

  • Duración de la lección: 6:17 min

[1]:
#
# Side effects con variables
# =============================================================================
#
a = 1
b = 2


def a_plus_b():
    return a + b


a_plus_b()
[1]:
3
[2]:
#
# Side effect:
# Un cambio inadvertido cambia cambios no esperados en el resultado de la
# función (indeseado!)
#
a = 3

a_plus_b()
[2]:
5
[3]:
#
# Side effects con listas
# =============================================================================
#
my_list = [1, 2]


def my_function(a_list):
    a_list.append("a")


my_function(my_list)
#
# Efecto indeseado:
#
print(my_list)
[1, 2, 'a']
[4]:
#
# Corrección: no se debe modificar la lista externa
#
my_list = [1, 2]


def my_function(a_list):
    a_list = a_list.copy()
    a_list.append("a")


my_function(my_list)
print(my_list)
[1, 2]
[5]:
#
# Si se desea modificar la lista
#
my_list = [1, 2]


def my_function(a_list):
    a_list = a_list.copy()
    a_list.append("a")
    return a_list


my_new_list = my_function(my_list)
print(my_list)
print(my_new_list)
[1, 2]
[1, 2, 'a']
[6]:
#
# Side effects con listas
# =============================================================================
# La variable L no debería acumular la lista ya que el valor por defecto
# de L es []
#
def f(a, L=[]):
    L.append(a)
    return L


print(f(1))
print(f(2))
print(f(3))
[1]
[1, 2]
[1, 2, 3]
[7]:
#
# Corrección del side effect usando None
#
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L


print(f(1))
print(f(2))
print(f(3))
[1]
[2]
[3]
[8]:
#
# Side effects con diccionarios
# =============================================================================
#
my_dict = {
    0: "a",
    1: "b",
}


def my_function(a_dict):
    a_dict[0] = "A"


my_function(my_dict)
#
# Efecto indeseado:
#
print(my_dict)
{0: 'A', 1: 'b'}
[9]:
my_dict = {
    0: "a",
    1: "b",
}


def my_function(a_dict):
    a_dict = a_dict.copy()
    a_dict[0] = "A"


my_function(my_dict)
print(my_dict)
{0: 'a', 1: 'b'}