RIIA in Python 2.5 alpha: "with... as"

Duncan Booth duncan.booth at invalid.invalid
Tue Apr 11 07:38:44 EDT 2006


Alexander Myodov wrote:

> So, with 2.5, I tried to utilize "with...as" construct for this, but
> unsuccessfully:
>    from __future__ import with_statement
>    with 5 as k:
>      pass
>    print k
> - told me that "AttributeError: 'int' object has no attribute
> '__context__'".
> 
> 
> So, does this mean that we still don't have any kind of RIIA in
> Python, any capability to localize the lifetime of variables on a
> level less than a function, and this is indeed not gonna happen to
> change yet?
> 

No, it means that Python 2.5 supports 'resource initialisation is 
acquisition', but that has nothing to do with the restricting the lifetime 
of a variable. You have to use a context manager to handle the resource, 5 
isn't a context manager. Some objects which actually need handling as a 
resource can be used as context managers, for others you might need to 
write your own.

with open('/etc/passwd', 'r') as f:
    for line in f:
        print line

after executing this f has been closed, but the variable f still exists.

Or try this:

>>> @contextlib.contextmanager
... def silly(n):
...    print "starting to use", n
...    yield n
...    print "finished with", n
...
>>> with silly(5) as k:
...    print "hello"
...
starting to use 5
hello
finished with 5
>>> k
5

The resource is controlled by the with statement, but the scope of the 
variable and the lifetime of the object are separate issues.



More information about the Python-list mailing list