Asignación por referencia

Escribir funciones en Python

Shayne Miel

Software Architect @ Duo Security

Un ejemplo sorprendente

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)
print(my_list)
[99, 2, 3]
def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
print(my_var)
3
Escribir funciones en Python

Más a fondo

RAM

Escribir funciones en Python

Más a fondo

a = [1, 2, 3]

definir a

Escribir funciones en Python

Más a fondo

a = [1, 2, 3]

b = a

b igual a a

Escribir funciones en Python

Más a fondo

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]

añadir a a

Escribir funciones en Python

Más a fondo

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]
b.append(5)

print(a)
[1, 2, 3, 4, 5]

añadir a b

Escribir funciones en Python

Más a fondo

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]
b.append(5)

print(a)
[1, 2, 3, 4, 5]
a = 42

a igual a 42

Escribir funciones en Python

Asignación por referencia

def foo(x):
  x[0] = 99

RAM

Escribir funciones en Python

Asignación por referencia

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]

definir my_list

Escribir funciones en Python

Asignación por referencia

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)

llamar a foo()

Escribir funciones en Python

Asignación por referencia

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)
print(my_list)
[99, 2, 3]

actualizar x y my_list

Escribir funciones en Python

Asignación por referencia

def bar(x):
  x = x + 90

my_var = 3

my_var

Escribir funciones en Python

Asignación por referencia

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)

llamar a bar()

Escribir funciones en Python

Asignación por referencia

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
my_var
3

asignar x a algo nuevo

Escribir funciones en Python

¿Inmutable o mutable?

Inmutables

  • int
  • float
  • bool
  • string
  • bytes
  • tuple
  • frozenset
  • None

Mutables

  • list
  • dict
  • set
  • bytearray
  • objetos
  • funciones
  • casi todo lo demás
Escribir funciones en Python

¡Los argumentos mutables por defecto son peligrosos!

def foo(var=[]):
  var.append(1)
  return var

foo()
[1]
foo()
[1, 1]
def foo(var=None):
  if var is None:
    var = []
  var.append(1)
  return var

foo()
[1]
foo()
[1]
Escribir funciones en Python

¡Vamos a practicar!

Escribir funciones en Python

Preparing Video For Download...