In this code snippet I forgot to define the variable content
in the outer scope. Then I assign a value to content
in the with
block. After leaving the with
block the value of the variable content
still exists. Why?
data_dir = "/Users/ugur/code/automating_tools/calibre"
kindle_drm_csv = "amazon_drm_books.csv"
csv_path = f"{data_dir}/{kindle_drm_csv}"
# I forgot to define this:
# content = ""
with open(csv_path, 'r', encoding='utf-8') as csv_file:
# read whole content
content = csv_file.read()
# why could I still print the content of the var?
# shouldn't it be undefined after leaving the `with` block?
print(content)
Also in this example:
if 3<10:
local_var = True
print(local_var)
# prints True
# why?
# I left the if-then-block.
# Shouldn't the local_var be undefined after leaving the block?
Python in not C. C automatic variables are indeed block scoped, but Python variables are either global or function scoped (*). As you are at the same function level, the variable declared in the block still exists after the end of the block.
(*) a corner case is that comprehensions are handled as hidden function. So a variable declared in a comprehension will hide any higher level scope variables of same name, and will vanish outside of the comprehension
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments