M
M
mkone1122021-12-22 06:21:19
Python
mkone112, 2021-12-22 06:21:19

Is it possible to determine in a function that it is called in a with context?

def in_with():
    # some magick

in_with()  # >> False
with open(...) as f:
    in_with()  # >> True

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
desaki, 2021-12-22
@desaki

Add print

M
Mikhail Krostelev, 2021-12-22
@twistfire92

Read about context managers. What is it, how to work with it.
As a sandbox, you can start with this code:

class func:

    def __init__(self):
        self.condition = 'вне контекста'

    # функция описывает методы, вызываемые при старте контекстного менеджера
    # Возвращаемое значение уходит в переменную var в конструкции 'with ... as var:'
    def __enter__(self):
        self.condition = 'в контексте'
        return self

    # Метод вызываемый в завершении конструкции with или при ошибке после нее
    def __exit__(self, type, value, traceback):
        pass

    def __call__(self):
        print(f'Выполнение функции {self.condition}')



out_context = func()
out_context()

print('-'*40)

with func() as inside_context:
    inside_context()

The result will be the following:
Выполнение функции вне контекста
----------------------------------------
Выполнение функции в контексте

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question