Questions tagged [contextmanager]

A python context manager manages the context of a with statement. A context manager defines enter and exit hooks that get called as the code block under the with statement is entered and exited, respectively.

Python’s creates a runtime context, defined by a context manager. As the code block under the with statement is entered, a __enter__ hook is called on the context manager, and as it is exited (by any means, including exceptions and return statements), the __exit__ hook is called.

Python provides several standard context managers. File objects, for example, can be opened as a context manager, and on exit the file is automatically closed.

Context managers were defined in PEP 343.

613 questions
0
votes
1 answer

using a context manager seems to change access to variables

I've got a working program that calls an API for each item of a list (say, a book) to get back metadata about the book. It stores the book : metadata in dict for use. This causes the user to wait during the metadata gathering, so avoid excess calls…
SQLesion
  • 165
  • 2
  • 9
0
votes
2 answers

How to get the "result" from a contextmanager using 'with'

I found a demo of a file locking class (here: https://groups.google.com/forum/#!topic/pug-pe/mQr7KX-cenU), but I don't quite understand the mechanics of using it. @contextmanager def FileLock(lock_file): if os.path.exists(lock_file): …
David Doria
  • 9,873
  • 17
  • 85
  • 147
0
votes
0 answers

How to use python context manager to "borrow" objects

I want to create a Python context manager to act as a controlled sort of "library" that lends out objects, and then takes them back when the scope of the with statement exits. In psuedo-code I was thinking something like this: class Library: def…
chew socks
  • 1,406
  • 2
  • 17
  • 37
0
votes
1 answer

Can Context Manager and Object Oriented be used effectively into a GAE Request Handler class

Can I use context manager inside a Request Handler to manage the flow of my variables from the URL to the template? I started from this example here I was thinking to use it to create a class instance at the top of the handler, to run all the code I…
tuned
  • 1,085
  • 10
  • 14
0
votes
1 answer

Store code inside a block as a function for execution later within that scope

This seems like something that might not be possible, but I'm trying to implement something like this: a = 0 with before(): a += 1 do_thing(a) # does thing with a, whose value is now 1 do_thing(a) # does thing with a, whose value is now 2 So I…
Eugene Bulkin
  • 1,068
  • 1
  • 13
  • 14
0
votes
1 answer

fabric: dealing with cd() in helper functions

In fabric, the cd context manager works like with cd("dir"): run("command") and the command will be run after changing to the dir directory. This works fine, but the issue is that it uses a global state. For example, suppose I have a helper…
asmeurer
  • 86,894
  • 26
  • 169
  • 240
-1
votes
0 answers

Factory session to mock context manager doesnt work

I can mock a context manager for a sqlalchemy session with: @patch("app.path_to_code.Session") def test_get_users_to_query(self, mock_session) -> None: self.engine = create_engine("sqlite:///:memory:") self.session = Session(self.engine) …
-1
votes
1 answer

How can I use a third-party context manager to run a custom-class's method?

In python, I'd like to use a with-statement context manager when using a particular third-party package because their context manager will handle clean-up for me in a best-practice way. Right now I have (say): class MyClass(object): def…
jtlz2
  • 7,700
  • 9
  • 64
  • 114
-1
votes
1 answer

Return statement behavior in "with" block inside a custom class-based context manager

Newer to Python and am experimenting with creating my own Context Manager for calling Login/Logout methods of a certain REST API. That way I can do other API things and Login/Logout will be handled for me. However, I'm confused on the behavior of…
-1
votes
2 answers

How can we create a decorator which will cause a function to use defintion-time variables instead of call-time variables?

Suppose that we create a decorator named deftime Consider the following piece of code: def LouiseTheLow(*ignore, **kw_ignore): print("I am Oldy McMold Face") @deftime def HarriettTheHigh(*ignored_args, **ignored_keywords): LouiseTheLow(59,…
-1
votes
2 answers

How to extract the full path from a file while using the "with" statement?

I'm trying, just for fun, to understand if I can extract the full path of my file while using the with statement (python 3.8) I have this simple code: with open('tmp.txt', 'r') as file: print(os.path.basename(file)) But I keep getting an error…
-1
votes
1 answer

Try finally block with generator in python

Can someone explain me the idea of generator and try except in this code: from contextlib import contextmanager @contextmanager def file_open(path): try: f_obj = open(path, 'w') yield f_obj except OSError: print("We…
jjjjake
  • 15
  • 4
-1
votes
2 answers

How to convert a list into a nested lists of fixed length

lets say i have text file 1234 5678 9012 3456 7890 1245 3678 4367 3454 4536 8768 1678 i want to extract all these into list and then convert that list into a list of lists of length say 2 so it should…
nsingh
  • 61
  • 1
  • 5
-1
votes
1 answer

Is there a pythonic way to mix error handling and context management?

I'd like to make a program which saves intermediate results to be able to reuse them is case of crash. In this regard, I wanted to try to open the intermediate results file with a context manager. However basic context manager do not include error…
Camion
  • 1,264
  • 9
  • 22
-1
votes
1 answer

How to create a new thread in the same code location. [python3]

I want to know if it is possible (and if so, then how) to create a new Thread without changing its 'location' in the code. An example probably explains it better: import time import random print('foo') # Should be printed only…
Keldan Chapman
  • 665
  • 5
  • 21
1 2 3
40
41