I have a csv file that has inconsistent spacing after the comma, like this: 534323, 93495443,34234234, 3523423423, 2342342,236555, 6564354344 I have written a function that tries to read in the file and makes the spacing consistent, but it doesn’t appear to update anything. After opening the new file cr…
Tag: with-statement
Why does calling the __exit__ method on unittest.mock._patch throw an IndexError?
When I define a function and patch it using the with statement it runs fine. Output: My understanding is that using the with statement would cause the __enter__ and __exit__ methods to be called on the patch object. So I thought that would be equivalent to doing this: The output from the some_func call is the…
Invoking a constructor in a ‘with’ statement
I have the following code: Running it produces the following output: But I expected it to produce: Why isn’t the code within my first example called? Answer The __enter__ method should return the context object. with … as … uses the return value of __enter__ to determine what object to give …
Execute code line by line interactively in console inside `with` block
When testing things interactively in a console, sometimes I use with statements. However, because they increase indentation, the prompt changes from >>> to … and the execution stops until I return to the lowest indentation. It makes sense for function definitions, because the code isn’t a…
Why can’t a module be a context manager (to a ‘with’ statement)?
Suppose we have the following mod.py: and the following use of it: I get an error: According to the documentation the documentation the with statement should execute as follows (I believe it fails at step 2 and therefore truncate the list): The context expression (the expression given in the with_item) is eva…
Is it possible to have an optional with/as statement in python?
Instead of this: it’s better to use this: What if I have something like this? Where do_something also has an “if FILE is None” clause, and still does something useful in that case – I don’t want to just skip do_something if FILE is None. Is there a sensible way of converting this…
Python with statement in C++
I am trying to implement something similar to the Python with statement in C++. As I plan to use it mainly with Qt-OpenGL the methods are called bind and release (in Python __enter__, __exit__). Code I came up with: header: cpp: Usage: Questions: Needing class A and class B feels a bit clumsy. Is there a bett…