[Python-Dev] Re: Use for enumerate

Barry A. Warsaw barry@zope.com
Sat, 27 Apr 2002 14:49:23 -0400

>>>>> "IK" == Ian Kjos <ikjos@email.uophx.edu> writes:

    IK> PS: This is a good argument for pre-object-death destructors
    IK> a'la C++. I think resources should be finalized as soon as
    IK> they are no longer accessable through other means. I realize
    IK> that there are issues to be resolved; perl does it by
    IK> following the law of most (!) astonishment. /me dives into
    IK> some documentation.

Here's a 5 minute toy example...


-------------------- snip snip --------------------/tmp/play.py
class resource:
    def __init__(self, resource, func):
        self.__resource = resource
        self.__func = func

    def __call__(self, *args, **kws):
            rtn = self.__func(*args, **kws)
        return rtn

class FileResource:
    def __init__(self, filename):
        self._filename = filename
        self._fp = None
        self.firstbyte = resource(self, self.firstbyte)

    def acquire(self):
        assert self._fp is None
        self._fp = file(self._filename)

    def release(self):
        assert self._fp is not None
        self._fp = None

    def firstbyte(self):
        return self._fp.read(1)

fr = FileResource('/tmp/play.py')
print 'firstbyte:', fr.firstbyte()
assert fr._fp is None