python file API

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 24 21:33:50 EDT 2012


On Tue, 25 Sep 2012 08:14:01 +1000, Chris Angelico wrote:

> Presumably the same way you reference a list element relative to
> end-of-list: negative numbers. However, this starts to feel like magic
> rather than attribute assignment - it's like manipulating the DOM in
> JavaScript, you set an attribute and stuff happens. Sure it's legal, but
> is it right? Also, it makes bounds checking awkward:
> 
> file.pos = 42 # Okay, you're at position 42 
> file.pos -= 10 # That should put you at position 32 
> foo = file.pos # Presumably foo is the integer 32
> file.pos -= 100 # What should this do? 
> foo -= 100 # But this sets foo to the integer -68 
> file.pos = foo # And this would set the file pointer 68 bytes
> from end-of-file.
> 
> I don't see it making sense for "file.pos -= 100" to suddenly put you
> near the end of the file; it should either cap and put you at position
> 0, or do what file.seek(-100,1) would do and throw an exception.

I would expect it to throw an exception, like file.seek and like list 
indexing.

> But
> doing the exact same operation on a saved snapshot of the position and
> reassigning it would then have quite different semantics in an unusual
> case, while still appearing identical in the normal case.

But this applies equally to file.seek and list indexing today. In neither 
case can you perform your own index operations outside of the file/list 
and expect to get the same result, for the simple and obvious reason that 
arithmetic doesn't perform the same bounds checking as actual seeking and 
indexing.

-- 
Steven



More information about the Python-list mailing list