Steven D'Aprano wrote: > On Mon, 13 Mar 2006 21:28:06 -0800, garyjefferson123 wrote: > > >>I'm having a scoping problem. I have a module called SpecialFile, >>which defines: >> (snip code)
>>The problem, if it isn't obvioius, is that the open() call in __init__ >>no longer refers to the builtin open(), but to the module open(). > > > In your code, open() is not a module, it is a function. Steven, it seems clear that the OP knows that already. Try reading the previous sentence as: """ The problem, if it isn't obvioius, is that the open() call in __init__ no longer refers to the builtin's open(), but to the module's open(). """ Does it make more sens ?-) > A better technique will be to turn open into a method of the class > SpecialFile, rather than a bare function. That way you keep open() the > built-in function separate from SpecialFile.open(). > > >>So, if I do: >> >>f = SpecialFile.open(name, mode) >> >>I get infinite recursion. > > > I see you are already using an open method. There again, you may want to read more carefully: SpecialFile is *also* the module's name - which, I agree, is not pythonic. (snip) > > I would handle it like this: > > class SpecialFile(object): > def __init__(self, fname, mode='r'): > self.fname = fname > self.mode = mode > def open(self): > self.f = open(self.fname, self.mode) > def close(self): > self.f.close() > def read(self): > return self.f.read() > def write(self, data): > self.f.write(data) > > You use it like so: > > sf = SpecialFile("hello.txt") > sf.open() > data = sf.read() > sf.close() Small variant, more builtins-open-like, and taking full advantage of Python's delegation mechanism: class SpecialFile(object): def __init__(self, fname, mode='r'): self.fname = fname self.mode = mode self._file = open(self.fname, self.mode) def __getattr__(self, name): return getattr(self._file) which allows: sf = SpecialFile("hello.txt") # then use it just like any other file object My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list