Passagem por atribuição

Como escrever funções em Python

Shayne Miel

Software Architect @ Duo Security

Um exemplo surpreendente

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
Como escrever funções em Python

Aprofundando

RAM

Como escrever funções em Python

Aprofundando

a = [1, 2, 3]

definindo a

Como escrever funções em Python

Aprofundando

a = [1, 2, 3]

b = a

b igual a a

Como escrever funções em Python

Aprofundando

a = [1, 2, 3]

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

adicionando em a

Como escrever funções em Python

Aprofundando

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]

adicionando em b

Como escrever funções em Python

Aprofundando

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

Como escrever funções em Python

Passagem por atribuição

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

RAM

Como escrever funções em Python

Passagem por atribuição

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

my_list = [1, 2, 3]

definindo my_list

Como escrever funções em Python

Passagem por atribuição

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

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

chamando foo()

Como escrever funções em Python

Passagem por atribuição

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

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

atualizando x e my_list

Como escrever funções em Python

Passagem por atribuição

def bar(x):
  x = x + 90

my_var = 3

my_var

Como escrever funções em Python

Passagem por atribuição

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)

chamando bar()

Como escrever funções em Python

Passagem por atribuição

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
my_var
3

atribuindo algo novo a x

Como escrever funções em Python

Imutável ou mutável?

Imutáveis

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

Mutáveis

  • list
  • dict
  • set
  • bytearray
  • objetos
  • funções
  • quase todo o resto!
Como escrever funções em Python

Defaults mutáveis são perigosos!

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]
Como escrever funções em Python

Vamos praticar!

Como escrever funções em Python

Preparing Video For Download...