Variable scoping

Related to

I was wondering how come following code executes, shouldn’t variable “encoding_name” go out of scope when the first context manager exits, how come the second context manager can still access it?

import csv
import chardet

with open('kyoto_restaurants.csv', mode='rb') as file:
    raw_bytes =
    encoding_name = chardet.detect(raw_bytes)['encoding']
with open('kyoto_restaurants.csv', encoding=encoding_name) as file:
    rows = list(csv.reader(file))

What happens when you google the following?

  1. python variable scope
  2. If block python scope
  3. with context manager python scope
  4. functions python scope

Here’s something harder to google.
Try locals(),globals(),vars() to look into what is there and what is not there.