Code Explanation:
1) from contextlib import contextmanager
Imports the contextmanager decorator from Python’s contextlib module.
This decorator allows you to write context managers (things used with with) as simple generator functions instead of full classes.
2) @contextmanager
This decorator marks the function below (tag) as a context manager factory.
Inside tag, the code before yield runs when entering the with block.
The code after yield runs when exiting the with block.
3) def tag(name):
Defines a generator function that takes name (like "p").
4) print(f"<{name}>")
When the with block starts, this line runs.
For name="p", it prints:
<p>
5) yield
The yield pauses execution of the context manager.
Control passes to the body of the with block (print("Hello")).
The value after yield could be passed to the as part of with, but here it’s unused.
6) print(f"</{name}>")
After the with block finishes, execution resumes after yield.
This prints:
</p>
7) with tag("p"):
Starts a with block using our custom context manager.
Enters tag("p"), which first prints <p>.
Then control goes into the with block.
8) print("Hello")
Runs inside the with block.
Prints:
Hello
Final Output
<p>
Hello
</p>
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment