contextmanager

Should a function that returns a context-managed object be decorated by `@contextmanager`?

Should a function that returns a context-managed object be decorated by `@contextmanager`? Question: Say I have a function that returns a context-managed object, here a tempfile.TemporaryFile: import tempfile def make_temp_file(): """Create a temporary file. Best used with a context manager""" tmpfile = tempfile.NamedTemporaryFile() return tmpfile Is this safe as is or should this be wrapped …

Total answers: 1

Why does my context manager not exit on exception

Why does my context manager not exit on exception Question: I am learning about context managers and was trying to build one myself. The following is a dummy context manager that opens a file in read mode (I know I can just do with open(…): …. this is just an example I built to help …

Total answers: 1

How to have Static and Method Functions with the same name

How to have Static and Method Functions with the same name Question: I’m trying to create a class for interacting with a MySQL Database. This class will connect to the database storing the connection object and cursor. Allowing for multiple actions without reconnecting every time. Once you’re done with it, the cursor and connection need …

Total answers: 1

What could be the problem in To-do app using Streamlit in Python?

What could be the problem in To-do app using Streamlit in Python? Question: to-dos.py import streamlit as st import get_todos todos = get_todos.getTodos() def add_todos(): todo1 = st.session_state["new_todo"] + "n" todos.append(todo1) get_todos.writeTodos(todos) st.title("My TO-DO App") … get_todos.py def getTodos(): with open("docs.txt", "r") as file: data = file.readlines() return data def writeTodos(adder): with open("docs.txt", "w") as …

Total answers: 1

How to use MLFlow in a functional style / functional programming?

How to use MLFlow in a functional style / functional programming? Question: Is there a reliable way to use MLFlow in a functional style? As it is not possible to pass the run ID for example to the function which logs a parameter, I wonder whether it is possible to seperate code executed in my …

Total answers: 2

Why do we need "try-finally" when using @contextmanager decorator?

Why do we need "try-finally" when using @contextmanager decorator? Question: I wonder why we need to use a try-finally when using a the @contextmanager decorator. The provided example suggests: from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): resource = acquire_resource(*args, **kwds) try: yield resource finally: release_resource(resource) It seems to me, however, that this will do …

Total answers: 2

Context manager: Error handling inside __init__ method

Context manager: Error handling inside __init__ method Question: A bit of context I am working with a package that allows you to calculate several things about planets (such as their speed, or position), using information stored in files. The package includes methods to load, and unload files, so its basic usage would look like this: …

Total answers: 1

Strange behavior with contextmanager

Strange behavior with contextmanager Question: Take a look at the following example: from contextlib import AbstractContextManager, contextmanager class MyClass(AbstractContextManager): _values = {} @contextmanager def using(self, name, value): print(f’Allocating {name} = {value}’) self._values[name] = value try: yield finally: print(f’Releasing {name}’) del self._values[name] def __enter__(self): return self.using(‘FOO’, 42).__enter__() def __exit__(self, exc_type, exc_val, exc_tb): pass with MyClass(): print(‘Doing …

Total answers: 1

How does contextmanager forward a raised exception to the function that it decorates?

How does contextmanager forward a raised exception to the function that it decorates? Question: How do I write a class that can be used in place of contextmanager in this example? from contextlib import contextmanager @contextmanager def f(): try: yield None except Exception as e: print(e) # This statement is executed! with f() as _: …

Total answers: 1

Why is __aexit__ not fully executed when it has await inside?

Why is __aexit__ not fully executed when it has await inside? Question: This is the simplified version of my code: main is a coroutine which stops after the second iteration. get_numbers is an async generator which yields numbers but within an async context manager. import asyncio class MyContextManager: async def __aenter__(self): print("Enter to the Context …

Total answers: 4