How do I make my own context manager?

0 votes
How do I create my own context manager using python? Also why do I need a context manager?
Aug 5 in Python by Trisha
18 views

1 answer to this question.

0 votes

Context is an opening file, catching expressions, etc. A context manager is anything that manages your context. You can use it like this:

from contextlib import contextmanager
 
def my_open(filename):
    file = open(filename)
 
    try:
        # this yield is where the body of the with statement happens
        yield file
    finally:
        file.close()
answered Aug 5 by Yamini

Related Questions In Python

0 votes
1 answer

How do I determine if my python shell is executing in 32bit or 64bit mode on OS X?

UPDATED: One way is to look at sys.maxsize as ...READ MORE

answered Dec 11, 2018 in Python by ariaholic
• 7,340 points
116 views
0 votes
0 answers

how do i install django in my system for the project?

can you tell me the procedure for ...READ MORE

May 3 in Python by Waseem
• 4,470 points
26 views
0 votes
0 answers

how do i get the list of all the keys in my dictionary?

can you give an example? with the ...READ MORE

May 6 in Python by Waseem
• 4,470 points
16 views
0 votes
1 answer

How do I make a delay in Python?

Hahah! Yes, you need to create a ...READ MORE

answered Jul 4 in Python by Pooja
33 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 351 views
+4 votes
6 answers
0 votes
1 answer

How do I make one turtle follow another turtle in python?

Try something like this: from turtle import Turtle, ...READ MORE

answered Jul 8 in Python by Ayushi
74 views
0 votes
1 answer

How do I upgrade my pycharm from python 2.7 to python 3?

Install Python 3.7(latest version) from the following ...READ MORE

answered Aug 5 in Python by Varsha
349 views