[Tutor] Proxies/Interceptors for file-like objects

spir denis.spir at free.fr
Thu Feb 19 09:56:11 CET 2009


Le Wed, 18 Feb 2009 22:01:34 -0500,
Kent Johnson <kent37 at tds.net> s'exprima ainsi:

> Hmm. I guess this is Python 3? In 2.6, open is a function and trying
> to subclass it gives an error:
> 
> In [10]: open
> Out[10]: <built-in function open>
> 
> In [11]: class myopen(open): pass
> 
>    ....:
> 
> TypeError: Error when calling the metaclass bases
>     cannot create 'builtin_function_or_method' instances

But... why not use the proper type instead:

class F(file):
	def __init__(self, file_name):
		self.file_name = file_name
f = F("/home/prog/io/test.py")
print dir(f)
print isinstance(f,types.FileType)
==>
['__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'file_name', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
True

Then, overload the proper method the call of which you need to catch. Or there is a "detail" I do not "catch" ;-)

Denis
------
la vita e estrany


More information about the Tutor mailing list