[Python-ideas] Automatic context managers

David Mertz mertz at gnosis.cx
Fri Apr 26 21:37:29 CEST 2013


On Apr 26, 2013, at 11:54 AM, random832 at fastmail.us wrote:
>> Ok. The proposal is patch Python to be able to write:
>> 
>>   boolean = open(resource).use()
>> 
>> Instead of:
>> 
>>   boolean = None
>>   with open(resource) as tempvar:
>>       boolean = tempvar.use()
> 
> What about a with expression?
> boolean = x.use() with x as open(resource)

The initial 'boolean=None' is superfluous in any case.  So the ideas are that instead of the current:

  with open(resources) as x: boolean = x.use()

We might right:

  boolean = open(resource).use()

Or:

  boolean = x.use() with x as open(resource)

The with expression saves two characters, the probably entirely unworkable "automatic context manager" would save 13 characters.  The existing one-liner seems perfectly clear to me and perfectly compact.

A "with expression" doesn't seem absurd to me, but I'm not sure that the percentage of the time you really do want a single expression inside the 'with' block is common enough to warrant a special form.  In contrast, the 'if expression' ternary operator that was introduced really does seem to express a very common pattern.

I'd note that there's no reason you couldn't use the so-called "automatic context manager" already, it's just a matter of writing your own function rather than the built-in 'open()'.  So, e.g. with a few lines of definition, you might use:

  boolean = SafeOpen(resource).use()



--
mertz@ | The specter of free information is haunting the `Net!  All the
gnosis | powers of IP- and crypto-tyranny have entered into an unholy
.cx    | alliance...ideas have nothing to lose but their chains.  Unite
       | against "intellectual property" and anti-privacy regimes!




More information about the Python-ideas mailing list