My first Python program

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Thu Oct 14 15:07:21 CEST 2010


Seebs writes:

>> You can't really rely on the destructor __del__ being called.
>
> Interesting.  Do I just rely on files getting closed?

Sometimes, but that's not it.  Think Lisp, not C++.  __del__ is not that
useful. Python is garbage-collected and variables have dynamic lifetime,
so the class cannot expect __del__ to be called in a timely manner.
Destructors have several issues, see __del__ in the Python reference.

A class which holds an OS resource like a file, should provide a context
manager and/or a release function, the latter usually called in a
'finally:' block.  When the caller doesn't bother with either, the class
often might as well depend on the destructor in 'file'.

Still, open().read() is common.  open().write() is not.  The C
implementation of Python is reference-counted on top of GC, so the file
is closed immediately.  But this way, exceptions from close() are lost.
Python cannot propagate them up the possibly-unrelated call chain.


Some other points:

For long strings, another option is triple-quoting as you've seen in doc
strings: print """foo
bar""".


class SourceFile(object):
    def emit(self, template, func = None):
            # hey, at least it's not a global variable, amirite?
            self.file.write(SourceFile.copyright)
def main():
    SourceFile.copyright = copyright_file.read()

emit() can use self.copyright instead of SourceFile.copyright.

I've written such code, but I suppose the proper way is to use a
classmethod to set it, so you can see in the class how the copyright
gets there.  SourceFile.<classmethod>() and self.<classmethod>() both
get called with the class as 1st argument.

class SourceFile(object):
    def setup_copyright(cls, fname):
        cls.copyright = open(fname).read()
    setup_copyright = classmethod(setup_copyright)
    # In python >= 2.4 you can instead say @classmethod above the def.
def main():
    SourceFile.setup_copyright('guts/COPYRIGHT')


SourceFile.__repr__() looks like it should be a __str__().  I haven't
looked at how you use it though.  But __repr__ is supposed to
look like a Python expression to create the instance: repr([2]) = '[2]',
or a generic '<foo instance>': repr(id) = '<built-in function id>'.


"How new are list comprehensions?"

Python 2.0, found as follows:
- Google python list comprehensions.
- Check the PEP (Python Enhancement Proposal) which shows up.  PEPs
  are the formal documents for info to the community, for the Python
  development process, etc.  <http://www.python.org/dev/peps/pep-0202/>:
    Title: 	    List Comprehensions
    Status: 	    Final
    Type: 	    Standards Track
    Python-Version: 2.0


-- 
Hallvard



More information about the Python-list mailing list