BOOKPYTHON Telegram 3372
Что такое контекстный менеджер в Python?

Контекстный менеджер в Python — это специальный тип объекта, который определяет методы enter() и exit() и используется с инструкцией with. Эти объекты часто применяются в операциях, которые требуют установки и освобождения ресурсов. 

Частый сценарий — это работа с файлом:


with open('file.txt', 'r') as file:
data = file.read()


Здесь контекстный менеджер гарантирует, что файл будет корректно закрыт после завершения блока with, даже если при чтении файла возникнет исключение.

Вот как можно написать простой контекстный менеджер самостоятельно:


import time

class Timer:
def __enter__(self):
self.start = time.time()

def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
print(f'Время выполнения: {self.end - self.start:.2f} секунд')

with Timer():
# код, время выполнения которого нужно измерить
time.sleep(2)


👉@BookPython
👍4👎1



tgoop.com/BookPython/3372
Create:
Last Update:

Что такое контекстный менеджер в Python?

Контекстный менеджер в Python — это специальный тип объекта, который определяет методы enter() и exit() и используется с инструкцией with. Эти объекты часто применяются в операциях, которые требуют установки и освобождения ресурсов. 

Частый сценарий — это работа с файлом:


with open('file.txt', 'r') as file:
data = file.read()


Здесь контекстный менеджер гарантирует, что файл будет корректно закрыт после завершения блока with, даже если при чтении файла возникнет исключение.

Вот как можно написать простой контекстный менеджер самостоятельно:


import time

class Timer:
def __enter__(self):
self.start = time.time()

def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
print(f'Время выполнения: {self.end - self.start:.2f} секунд')

with Timer():
# код, время выполнения которого нужно измерить
time.sleep(2)


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Share with your friend now:
tgoop.com/BookPython/3372

View MORE
Open in Telegram


Telegram News

Date: |

Members can post their voice notes of themselves screaming. Interestingly, the group doesn’t allow to post anything else which might lead to an instant ban. As of now, there are more than 330 members in the group. In the next window, choose the type of your channel. If you want your channel to be public, you need to develop a link for it. In the screenshot below, it’s ”/catmarketing.” If your selected link is unavailable, you’ll need to suggest another option. Some Telegram Channels content management tips Earlier, crypto enthusiasts had created a self-described “meme app” dubbed “gm” app wherein users would greet each other with “gm” or “good morning” messages. However, in September 2021, the gm app was down after a hacker reportedly gained access to the user data. Co-founder of NFT renting protocol Rentable World emiliano.eth shared the group Tuesday morning on Twitter, calling out the "degenerate" community, or crypto obsessives that engage in high-risk trading.
from us


Telegram Библиотека Python разработчика | Книги по питону
FROM American