Variable scoping

Related to https://app.dataquest.io/m/452/reading-and-writing-to-files/6/encoding-identification-workflow

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 = file.read(32)
    encoding_name = chardet.detect(raw_bytes)['encoding']
    print(encoding_name)
    
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.