Skip to content

Commit

Permalink
Add a more elaborate description to the side effects section
Browse files Browse the repository at this point in the history
  • Loading branch information
zedr committed Jul 5, 2019
1 parent 9d712ab commit 4112718
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -549,17 +549,24 @@ If you can do this, you will be happier than the vast majority of other programm
**Bad:**

```python
# Global variable referenced by following function.
# If another function used this name, now it'd be an array and could break.
# This is a module-level name.
# It's good practice to define these as immutable values, such as a string.
# However...
name = 'Ryan McDermott'

def split_into_first_and_last_name() -> None:
# The use of the global keyword here is changing the meaning of the
# the following line. This function is now mutating the module-level
# state and introducing a side-effect!
global name
name = name.split()

split_into_first_and_last_name()

print(name) # ['Ryan', 'McDermott']

# OK. It worked the first time, but what will happen if we call the
# function again?
```

**Good:**
Expand All @@ -586,6 +593,7 @@ class Person:
def name_as_first_and_last(self) -> list:
return self.name.split()

# The reason why we create instances of classes is to manage state!
person = Person('Ryan McDermott')
print(person.name) # 'Ryan McDermott'
print(person.name_as_first_and_last) # ['Ryan', 'McDermott']
Expand Down

0 comments on commit 4112718

Please sign in to comment.