Transmettre par affectation

Écrire des fonctions en Python

Shayne Miel

Software Architect @ Duo Security

Un exemple surprenant

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
Écrire des fonctions en Python

Approfondissement

RAM

Écrire des fonctions en Python

Approfondissement

a = [1, 2, 3]

setting a

Écrire des fonctions en Python

Approfondissement

a = [1, 2, 3]

b = a

b equals a

Écrire des fonctions en Python

Approfondissement

a = [1, 2, 3]

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

append to a

Écrire des fonctions en Python

Approfondissement

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]

append to b

Écrire des fonctions en Python

Approfondissement

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 equals 42

Écrire des fonctions en Python

Transmettre par affectation

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

RAM

Écrire des fonctions en Python

Transmettre par affectation

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

my_list = [1, 2, 3]

setting my_list

Écrire des fonctions en Python

Transmettre par affectation

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

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

calling foo()

Écrire des fonctions en Python

Transmettre par affectation

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

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

updating x and my_list

Écrire des fonctions en Python

Transmettre par affectation

def bar(x):
  x = x + 90

my_var = 3

my_var

Écrire des fonctions en Python

Transmettre par affectation

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)

calling bar()

Écrire des fonctions en Python

Transmettre par affectation

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
my_var
3

assign x to something new

Écrire des fonctions en Python

Immuable ou mutable ?

Immuable

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

Mutable

  • list
  • dict
  • set
  • bytearray
  • objects
  • functions
  • presque tout le reste !
Écrire des fonctions en Python

Les arguments par défaut modifiables peuvent être problématiques.

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]
Écrire des fonctions en Python

Passons à la pratique !

Écrire des fonctions en Python

Preparing Video For Download...