[Python-3000] enhanced descriptors

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Jun 11 01:50:09 CEST 2006


tomer filiba wrote:

> i did think of doing a position-proxy class, but it has lots of
> drawbacks as well:
> * lots of methods to implement (to make it look like an int)

Not if you subclass it from int, and inherit all its
behaviour. The only things you'd need to add are a
reference to the base file object, and __iadd__ and
__isub__ methods.

> * lazy evaluation -- should only perform tell() when requested,
> not before. for example, calling __repr__ or __add__ would have
> to tell(), while __iadd__ would not... nasty code

Yes, I hadn't thought of that. Quite nasty, especially
since code that got the position of a file, did something
else that changed the file position, and *then* used the
position it got before, would get unexpected results.

> any good solution would require lots of magic, so i guess
> i'm just gonna pull off the += optimization. two system calls
> are not worth writing such an ugly code.

Yes, I'm coming to the same conclusion. Without changing
the language, the desired behaviour isn't reasonably
attainable.

> i'm afraid that's not possible, because the compiler can't tell
> that x.y+=z is a descriptor assignment.

It wouldn't operate at the descriptor level, it would
operate on the object itself, i.e. it would call
x.__iattr__('y', '+=', z) or some such.

So in your case you wouldn't use a descriptor for this
part, but give the file object an __iattr__ method.

> no, i don't think so. indexing should first __get__ the object,
> and then index it. these are two separate operations. only the
> inplace operators should be optimized into one function.

I'm talking about using an in-place operator on the
result of an indexing operation, e.g.

   x[i] += y

which is a closely analogous situation. Not needed for
this particular use case -- I'm just thinking ahead.

--
Greg


More information about the Python-3000 mailing list