Evaluate and assign expression in or before with statement

Viewed 67

If I am correct, with statement doesn't introduce a local scope for the with statement.

These are examples from Learning Python:

with open(r'C:\misc\data') as myfile:
    for line in myfile:
        print(line)
        ...more code here...

and

lock = threading.Lock()                        # After: import threading
with lock:
    # critical section of code
    ...access shared resources...

Is the second example equivalent to the following rewritten in a way similar to the first example?

with threading.Lock() as lock:
    # critical section of code
    ...access shared resources...

What are their differences?

Is the first example equivalent to the following rewritten in a way similar to the second example?

myfile = open(r'C:\misc\data')
with myfile:
    for line in myfile:
        print(line)
        ...more code here...

What are their differences?

2 Answers
Related