0

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?
Ugur
  • 1,914
  • 2
  • 25
  • 46
  • @Philipp Excellent. Thanks. But still: My second example cannot be explained with your link. – Ugur Apr 16 '20 at 14:54
  • The first line of the accepted answer in the thread I sent states that with, if, for and while do not create a scope in Python. Does that explain your question in the second example? – philipp Apr 16 '20 at 15:01
  • Yes it does. Thanks! – Ugur Apr 16 '20 at 15:02

3 Answers3

3

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

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

There is no local scope (block scope) in python, only function and global scope.

1

In Python, with and if do not create their own scope. In the code you have provided, content and local_var are created in the global scope and are thus accessible outside of the with and if statements. The only Python constructs that create their own scope are modules, classes, functions, generator expressions, and dict/set/list comprehensions.

clamchowder314
  • 223
  • 2
  • 8
  • So is it not a good practice to define a variable prior to using it in an `if` block or `with` block? – Ugur Apr 16 '20 at 15:01