5.3. Argument Mutability

5.3.1. Rationale

  • Function and method arguments should not be mutable

5.3.2. Immutable Types

  • int

  • float

  • complex

  • bool

  • None

  • str

  • bytes

  • tuple

  • frozenset

5.3.3. Mutable Types

  • list

  • set

  • dict

5.3.4. Case Study

Listing 5.91. Bad
class Astronaut:
    def __init__(self, name, missions=[]):
        self.name = name
        self.missions = missions


watney = Astronaut('Mark Watney')
watney.missions.append('Ares 3')
print('Watney:', watney.missions)
# Watney: ['Ares 3']

twardowski = Astronaut('Jan Twardowski')
print('Twardowski:', twardowski.missions)
# 'Twardowski:' ['Ares 3']
Listing 5.92. Good
class Astronaut:
    def __init__(self, name, missions=()):
        self.name = name
        self.missions = list(missions)


watney = Astronaut('Mark Watney')
watney.missions.append('Ares 3')
print('Watney:', watney.missions)
# Watney: ['Ares 3']

twardowski = Astronaut('Jan Twardowski')
print('Twardowski:', twardowski.missions)
# 'Twardowski:' []

5.3.5. Assignments

Todo

Create assignments