From: Mike Kent on
On Mar 3, 12:00 pm, Robert Kern <robert.k...(a)gmail.com> wrote:
> On 2010-03-03 09:39 AM, Mike Kent wrote:
>
> > What's the compelling use case for this vs. a simple try/finally?
>
> >     original_dir = os.getcwd()
> >     try:
> >         os.chdir(somewhere)
> >         # Do other stuff
> >     finally:
> >         os.chdir(original_dir)
> >         # Do other cleanup
>
> A custom-written context manager looks nicer and can be more readable.
>
> from contextlib import contextmanager
> import os
>
> @contextmanager
> def pushd(path):
>      original_dir = os.getcwd()
>      os.chdir(path)
>      try:
>          yield
>      finally:
>          os.chdir(original_dir)
>
> with pushd(somewhere):
>      ...

Robert, I like the way you think. That's a perfect name for that
context manager! However, you can clear one thing up for me... isn't
the inner try/finally superfluous? My understanding was that there
was an implicit try/finally already done which will insure that
everything after the yield statement was always executed.
From: Alf P. Steinbach on
* Mike Kent:
> On Mar 4, 12:30 pm, Robert Kern <robert.k...(a)gmail.com> wrote:
>
>> He's ignorant of the use cases of the with: statement, true.
>
> <humor> Ouch! Ignorant of the use cases of the with statement, am I?
> Odd, I use it all the time. </humor>
>
>> Given only your
>> example of the with: statement, it is hard to fault him for thinking that try:
>> finally: wouldn't suffice.
>
> <humor> Damn me with faint praise, will you? </humor>
>
> I'm kinda amazed at the drama my innocent request for the use case
> elicited. From what I've gotten so far from this thread, for the
> actual example Mr. Steinbach used, the only disadvantage to my counter-
> example using try/finally is that the chdir in the finally part will
> always be executed, even if the chdir in the try part did not
> succeed. I concede that, and was aware of it when I wrote it. For
> the simple example given, I did not consider it compelling.

Uhm, well.

My example was:

with Cleanup as at_cleanup:
# blah blah
chdir( somewhere )
at_cleanup.call( lambda: chdir( original_dir ) )
# blah blah

It was not intended to compel, rather just to illustrate usage. :-)

And you asked about comparing that with ...

original_dir = os.getcwd()
try:
os.chdir(somewhere)
# Do other stuff
finally:
os.chdir(original_dir)
# Do other cleanup

... which does something different, namely, always executing the
os.chdir(original_dir) or more generally the action-specific cleanup.

The action-specific cleanup might be much more costly than a chdir, and/or, in
the case where the action failed, incorrect.

In the same number of lines and with fewer keystrokes you could have written
code that was equivalent to the code I posted and that you wanted to compare
with, e.g. ...

original_dir = os.getcwd()
os.chdir(somewhere)
try:
# Do other stuff
finally:
os.chdir(original_dir)
# Do other cleanup

.... so given how easy it is to write such an equivalent code snippet, I assumed
that the different behavior was /not/ intended, that instead, you'd attempted to
write equivalent code but made a slight error in the translation to lower level
construct -- but impossible to say exactly what.

Now you write that you were "aware of [the different behavior] when I wrote it",
and that just baffles me: why not then, as a basis of sound comparision, write
the equivalent code shown above, the same number of lines as what you wrote?


> A more
> complex example, that would have required multiple, nested try/finally
> blocks, would show the advantages of Mr Steinbach's recipe more
> clearly.
>
> However, I fail to understand his response that I must have meant try/
> else instead, as this, as Mr. Kern pointed out, is invalid syntax.
> Perhaps Mr. Steinbach would like to give an example?

OK.

Assuming that you wanted the chdir to be within a try block (which it was in
your code), then to get code equivalent to my code, for the purpose of a
comparision of codes that do the same, you'd have to write something like ...

original_dir = os.getcwd()
try:
os.chdir(somewhere)
except Whatever:
# E.g. log it.
raise
else:
try:
# Do other stuff
finally:
os.chdir(original_dir)
# Do other cleanup

.... which would be a more general case.

I've also given this example in response to Robert earlier in the thread.
Although I haven't tried it I believe it's syntactically valid. If not, then the
relevant typo should just be fixed. :-)

I have no idea which construct Robert thought was syntactically invalid. I think
that if he's written that, then it must have been something he thought of.


Cheers & hth.,

- Alf
From: Robert Kern on
On 2010-03-04 12:37 PM, Alf P. Steinbach wrote:
> * Robert Kern:
>> On 2010-03-04 10:56 AM, Alf P. Steinbach wrote:
>>> * Robert Kern:
>>>> On 2010-03-03 18:49 PM, Alf P. Steinbach wrote:
> [snippety]
>>>>
>>>>> If you call the possibly failing operation "A", then that systematic
>>>>> approach goes like this: if A fails, then it has cleaned up its own
>>>>> mess, but if A succeeds, then it's the responsibility of the calling
>>>>> code to clean up if the higher level (multiple statements) operation
>>>>> that A is embedded in, fails.
>>>>>
>>>>> And that's what Marginean's original C++ ScopeGuard was designed for,
>>>>> and what the corresponding Python Cleanup class is designed for.
>>>>
>>>> And try: finally:, for that matter.
>>>
>>> Not to mention "with".
>>>
>>> Some other poster made the same error recently in this thread; it is a
>>> common fallacy in discussions about programming, to assume that since
>>> the same can be expressed using lower level constructs, those are all
>>> that are required.
>>>
>>> If adopted as true it ultimately means the removal of all control
>>> structures above the level of "if" and "goto" (except Python doesn't
>>> have "goto").
>>
>> What I'm trying to explain is that the with: statement has a use even
>> if Cleanup doesn't. Arguing that Cleanup doesn't improve on try:
>> finally: does not mean that the with: statement doesn't improve on
>> try: finally:.
>
> That's a different argument, essentially that you see no advantage for
> your current coding patterns.
>
> It's unconnected to the argument I responded to.
>
> The argument that I responded to, that the possibility of expressing
> things at the level of try:finally: means that a higher level construct
> is superfluous, is still meaningless.

I am attacking your premise that the "with Cleanup():" construct is higher level
than try: finally:. It isn't. It provides the same level of abstraction as try:
finally:.

This is distinct from the accepted uses of the with: statement which *are*
higher level than try: finally: and which do confer practical benefits over
using try: finally: despite being syntactical sugar for try: finally:.

>>>>>> Both formulations can be correct (and both work perfectly fine with
>>>>>> the chdir() example being used). Sometimes one is better than the
>>>>>> other, and sometimes not. You can achieve both ways with either your
>>>>>> Cleanup class or with try: finally:.
>>>>>>
>>>>>> I am still of the opinion that Cleanup is not an improvement over
>>>>>> try:
>>>>>> finally: and has the significant ugliness of forcing cleanup code
>>>>>> into
>>>>>> callables. This significantly limits what you can do in your cleanup
>>>>>> code.
>>>>>
>>>>> Uhm, not really. :-) As I see it.
>>>>
>>>> Well, not being able to affect the namespace is a significant
>>>> limitation. Sometimes you need to delete objects from the namespace in
>>>> order to ensure that their refcounts go to zero and their cleanup code
>>>> gets executed.
>>>
>>> Just a nit (I agree that a lambda can't do this, but as to what's
>>> required): assigning None is sufficient for that[1].
>>
>> Yes, but no callable is going to allow you to assign None to names in
>> that namespace, either. Not without sys._getframe() hackery, in any case.
>>
>>> However, note that the current language doesn't guarantee such cleanup,
>>> at least as far as I know.
>>>
>>> So while it's good practice to support it, to do everything to let it
>>> happen, it's presumably bad practice to rely on it happening.
>>>
>>>
>>>> Tracebacks will keep the namespace alive and all objects in it.
>>>
>>> Thanks!, I hadn't thought of connecting that to general cleanup actions.
>>>
>>> It limits the use of general "with" in the same way.
>>
>> Not really.
>
> Sorry, it limits general 'with' in /exactly/ the same way.
>
>> It's easy to write context managers that do that [delete objects from
>> the namespace].
>
> Sorry, no can do, as far as I know; your following example quoted below
> is an example of /something else/.

Okay, so what do you mean by 'the use of general "with"'? I'm talking about
writing a context manager or using the @contextmanager decorator to do some
initialization and then later cleaning up that initialization. That cleaning up
may entail deleting an object. You are correct that the context manager can't
affect the namespace of the with: clause, but that's not the initialization that
it would need to clean up.

Yes, you can write code with a with: statement where you try to clean up stuff
that happened inside of the clause (you did), but that's not how the with:
statement was ever intended to be used nor is it good practice to do so because
of that limitation. Context managers are designed to initialize specific things,
then clean them up. I thought you were talking about the uses of the with:
statement as described in PEP-343, not every possible misuse of the with: statement.

> And adding on top of irrelevancy, for the pure technical aspect it can
> be accomplished in the same way using Cleanup (I provide an example below).
>
> However, doing that would generally be worse than pointless since with
> good coding practices the objects would become unreferenced anyway.
>
>
>> You put the initialization code in the __enter__() method, assign
>> whatever objects you want to keep around through the with: clause as
>> attributes on the manager, then delete those attributes in the
>> __exit__().
>
> Analogously, if one were to do this thing, then it could be accomplished
> using a Cleanup context manager as follows:
>
> foo = lambda: None
> foo.x = create_some_object()
> at_cleanup.call( lambda o = foo: delattr( o, "x" ) )
>
> ... except that
>
> 1) for a once-only case this is less code :-)

Not compared to a try: finally:, it isn't.

> 2) it is a usage that I wouldn't recommend; instead I recommend adopting
> good
> coding practices where object references aren't kept around.

Many of the use cases of the with: statement involve creating an object (like a
lock or a transaction object), keeping it around for the duration of the "# Do
stuff" block, and then finalizing it.

>> Or, you use the @contextmanager decorator to turn a generator into a
>> context manager, and you just assign to local variables and del them
>> in the finally: clause.
>
> Uhm, you don't need a 'finally' clause when you define a context manager.

When you use the @contextmanager decorator, you almost always do. See the
Examples section of PEP 343:

http://www.python.org/dev/peps/pep-0343/

> Additionally, you don't need to 'del' the local variables in
> @contextmanager decorated generator.
>
> The local variables cease to exist automatically.

True.

>> What you can't do is write a generic context manager where the
>> initialization happens inside the with: clause and the cleanup actions
>> are registered callables. That does not allow you to affect the
>> namespace.
>
> If you mean that you can't introduce direct local variables and have
> them deleted by "registered callables" in a portable way, then right.
>
> But I can't think of any example where that would be relevant; in
> particular what matters for supporting on-destruction cleanup is whether
> you keep any references or not, not whether you have a local variable of
> any given name.

Well, local variables keep references to objects. Variable assignment followed
by deletion is a very readable way to keep an object around for a while then
remove it later. If you have to go through less readable contortions to keep the
object around when it needs to be and clean it up later, then that is a mark
against your approach.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

From: Alf P. Steinbach on
* Robert Kern:
> On 2010-03-04 12:37 PM, Alf P. Steinbach wrote:
>> * Robert Kern:
>>> On 2010-03-04 10:56 AM, Alf P. Steinbach wrote:
>>>> * Robert Kern:
>>>>> On 2010-03-03 18:49 PM, Alf P. Steinbach wrote:
>> [snippety]
>>>>>
>>>>>> If you call the possibly failing operation "A", then that systematic
>>>>>> approach goes like this: if A fails, then it has cleaned up its own
>>>>>> mess, but if A succeeds, then it's the responsibility of the calling
>>>>>> code to clean up if the higher level (multiple statements) operation
>>>>>> that A is embedded in, fails.
>>>>>>
>>>>>> And that's what Marginean's original C++ ScopeGuard was designed for,
>>>>>> and what the corresponding Python Cleanup class is designed for.
>>>>>
>>>>> And try: finally:, for that matter.
>>>>
>>>> Not to mention "with".
>>>>
>>>> Some other poster made the same error recently in this thread; it is a
>>>> common fallacy in discussions about programming, to assume that since
>>>> the same can be expressed using lower level constructs, those are all
>>>> that are required.
>>>>
>>>> If adopted as true it ultimately means the removal of all control
>>>> structures above the level of "if" and "goto" (except Python doesn't
>>>> have "goto").
>>>
>>> What I'm trying to explain is that the with: statement has a use even
>>> if Cleanup doesn't. Arguing that Cleanup doesn't improve on try:
>>> finally: does not mean that the with: statement doesn't improve on
>>> try: finally:.
>>
>> That's a different argument, essentially that you see no advantage for
>> your current coding patterns.
>>
>> It's unconnected to the argument I responded to.
>>
>> The argument that I responded to, that the possibility of expressing
>> things at the level of try:finally: means that a higher level construct
>> is superfluous, is still meaningless.
>
> I am attacking your premise that the "with Cleanup():" construct is
> higher level than try: finally:. It isn't. It provides the same level of
> abstraction as try: finally:.
>
> This is distinct from the accepted uses of the with: statement which
> *are* higher level than try: finally: and which do confer practical
> benefits over using try: finally: despite being syntactical sugar for
> try: finally:.
>
>>>>>>> Both formulations can be correct (and both work perfectly fine with
>>>>>>> the chdir() example being used). Sometimes one is better than the
>>>>>>> other, and sometimes not. You can achieve both ways with either your
>>>>>>> Cleanup class or with try: finally:.
>>>>>>>
>>>>>>> I am still of the opinion that Cleanup is not an improvement over
>>>>>>> try:
>>>>>>> finally: and has the significant ugliness of forcing cleanup code
>>>>>>> into
>>>>>>> callables. This significantly limits what you can do in your cleanup
>>>>>>> code.
>>>>>>
>>>>>> Uhm, not really. :-) As I see it.
>>>>>
>>>>> Well, not being able to affect the namespace is a significant
>>>>> limitation. Sometimes you need to delete objects from the namespace in
>>>>> order to ensure that their refcounts go to zero and their cleanup code
>>>>> gets executed.
>>>>
>>>> Just a nit (I agree that a lambda can't do this, but as to what's
>>>> required): assigning None is sufficient for that[1].
>>>
>>> Yes, but no callable is going to allow you to assign None to names in
>>> that namespace, either. Not without sys._getframe() hackery, in any
>>> case.
>>>
>>>> However, note that the current language doesn't guarantee such cleanup,
>>>> at least as far as I know.
>>>>
>>>> So while it's good practice to support it, to do everything to let it
>>>> happen, it's presumably bad practice to rely on it happening.
>>>>
>>>>
>>>>> Tracebacks will keep the namespace alive and all objects in it.
>>>>
>>>> Thanks!, I hadn't thought of connecting that to general cleanup
>>>> actions.
>>>>
>>>> It limits the use of general "with" in the same way.
>>>
>>> Not really.
>>
>> Sorry, it limits general 'with' in /exactly/ the same way.
>>
>>> It's easy to write context managers that do that [delete objects from
>>> the namespace].
>>
>> Sorry, no can do, as far as I know; your following example quoted below
>> is an example of /something else/.
>
> Okay, so what do you mean by 'the use of general "with"'? I'm talking
> about writing a context manager or using the @contextmanager decorator
> to do some initialization and then later cleaning up that
> initialization. That cleaning up may entail deleting an object. You are
> correct that the context manager can't affect the namespace of the with:
> clause, but that's not the initialization that it would need to clean up.
>
> Yes, you can write code with a with: statement where you try to clean up
> stuff that happened inside of the clause (you did), but that's not how
> the with: statement was ever intended to be used nor is it good practice
> to do so because of that limitation. Context managers are designed to
> initialize specific things, then clean them up. I thought you were
> talking about the uses of the with: statement as described in PEP-343,
> not every possible misuse of the with: statement.

I'm not the one talking about removing variables or that "it's easy to write
context managers that do that".

You are the one talking about that.

So I have really not much to add.

It seems that you're now agreeing with me that former is not good practice and
that the latter is impossible to do portably, but you now argue against your
earlier stand as if that was something that I had put forward.

It's a bit confusing when you argue against your own statements.


>> And adding on top of irrelevancy, for the pure technical aspect it can
>> be accomplished in the same way using Cleanup (I provide an example
>> below).
>>
>> However, doing that would generally be worse than pointless since with
>> good coding practices the objects would become unreferenced anyway.
>>
>>
>>> You put the initialization code in the __enter__() method, assign
>>> whatever objects you want to keep around through the with: clause as
>>> attributes on the manager, then delete those attributes in the
>>> __exit__().
>>
>> Analogously, if one were to do this thing, then it could be accomplished
>> using a Cleanup context manager as follows:
>>
>> foo = lambda: None
>> foo.x = create_some_object()
>> at_cleanup.call( lambda o = foo: delattr( o, "x" ) )
>>
>> ... except that
>>
>> 1) for a once-only case this is less code :-)
>
> Not compared to a try: finally:, it isn't.

Again, this context shifting is bewildering. As you can see, quoted above, you
were talking about a situation where you would have defined a context manager,
presumably because a 'try' would not in your opinion be simpler for whatever it
was that you had in mind. But you are responding to the code I offered as if it
was an alternative to something where you would find a 'try' to be simplest.


>> 2) it is a usage that I wouldn't recommend; instead I recommend adopting
>> good
>> coding practices where object references aren't kept around.
>
> Many of the use cases of the with: statement involve creating an object
> (like a lock or a transaction object), keeping it around for the
> duration of the "# Do stuff" block, and then finalizing it.
>
>>> Or, you use the @contextmanager decorator to turn a generator into a
>>> context manager, and you just assign to local variables and del them
>>> in the finally: clause.
>>
>> Uhm, you don't need a 'finally' clause when you define a context manager.
>
> When you use the @contextmanager decorator, you almost always do. See
> the Examples section of PEP 343:
>
> http://www.python.org/dev/peps/pep-0343/
>
>> Additionally, you don't need to 'del' the local variables in
>> @contextmanager decorated generator.
>>
>> The local variables cease to exist automatically.
>
> True.
>
>>> What you can't do is write a generic context manager where the
>>> initialization happens inside the with: clause and the cleanup actions
>>> are registered callables. That does not allow you to affect the
>>> namespace.
>>
>> If you mean that you can't introduce direct local variables and have
>> them deleted by "registered callables" in a portable way, then right.
>>
>> But I can't think of any example where that would be relevant; in
>> particular what matters for supporting on-destruction cleanup is whether
>> you keep any references or not, not whether you have a local variable of
>> any given name.
>
> Well, local variables keep references to objects. Variable assignment
> followed by deletion is a very readable way to keep an object around for
> a while then remove it later. If you have to go through less readable
> contortions to keep the object around when it needs to be and clean it
> up later, then that is a mark against your approach.

Sorry, as with the places noted above, I can't understand what you're trying to
say here. I don't recommend coding practices where you keep object references
around, and you have twice quoted that above. I don't have any clue what
"contortions" you are talking about, it must be something that you imagine.


Cheers,

- Alf (three times baffled)
From: Steve Holden on
Alf P. Steinbach wrote:
> * Robert Kern:
[...]
>> No, it only argues that "with Cleanup():" is supernumerary.
>
> I don't know what "supernumerary" means, but to the degree that the
> argument says anything about a construct that is not 'finally', it says
> the same about general "with".
>
So rather than look up the meaning if a word you aren't familiar with
you will argue against its use in generic style?

> So whatever you mean by supernumerary, you're saying that the argument
> implies that "with" is supernumerary.
>
> This is starting to look like some earlier discussions in this group,
> where even basic logic is denied.
>
Why not just stick to the facts and forget about the earlier discussions?

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

First  |  Prev  |  Next  |  Last
Pages: 1 2 3 4 5 6 7 8 9 10 11
Prev: Few early questions on Class
Next: SOAP 1.2 Python client ?