Memory footprint of a class instance

Mike Meyer mwm at mired.org
Thu Feb 20 11:06:36 EST 2003


dromedary <camel at oasis.com> writes:

> A beginner's question:
> 
> Suppose I set up a class to handle files intended for text processing,
> and I make a class that looks like so:
> 
> class FileInit:
> 
>    def __init__(self, path):
>       self.pointer = open(path)
>       self.string = open(path).read()  
>       self.list = open(path).readlines()
> 
> Then I instantiate the class like so:
> 
> fh = FileInit('MY-PATH')
> Have I then already read the file into fh.string and fh.list, or do
> they exist only if I call them by, say, 
> print fh.string

They exist as when the instance is created.
> 
> I'm using large lists of words, and I wonder if I'll gum up the works
> by creating big list and string objects right off the bat.
> 
> BTW, the reason for the class is that when I've used this code
> f = open('MY-PATH').read()
[repeated reads fail.]

That's because you've already read it once. Use seek to reset
it. Assuming you want self.pointer at the start of the file, and using
the new, improved 2.2 name:

        def __init__(self, path):
            self.pointer = file(path)
            self.string = self.pointer.read()
            self.pointer.seek(0)
            self.list = self.pointer.readlines()
            self.pointer.seek(0)

This has the advantage of not relying on the garbage collector to
close the extra files you opened, which is a bad idea.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list