print bypasses calling write method for objects inheriting from file?

M

MisterPete

I created an object that inherits from file and was a bit surprised to
find that print seems to bypass the write method for objects
inheriting from file. An optimization I suppose. Does this surprise
anyone else at all or am I missing something?

import sys

class FromObject(object):

def write(self, string):
# this works fine, gets called by print
sys.stdout.write("FromObject: " + string)

class FromFile(file):

def __init__(self, name, mode='w'):
file.__init__(self, name, mode)

def write(self, string):
# this does not get called by print
sys.stdout.write("FromFile: " + string)


a = FromObject()
b = FromFile("test.txt")

a.write("Foo\n") # works as expected
b.write("Bar\n") # works as expected

print >> a, "Baz\n"
# "FromFile: Baz\nFromFile:\n" written to stdout. That's fine.

print >> b, "Qux\n"
b.flush()
# "Qux\n" written to test.txt. b.write wasn't called :(
 
P

Peter Otten

MisterPete said:
I created an object that inherits from file and was a bit surprised to
find that print seems to bypass the write method for objects
inheriting from file. An optimization I suppose. Does this surprise
anyone else at all or am I missing something?

No, your analysis is correct, though I'd consider optimization an euphemism
for bug here. Noone was annoyed enough to write a patch, it seems.

Peter
 
G

Gabriel Genellina

No, your analysis is correct, though I'd consider optimization an
euphemism
for bug here. Noone was annoyed enough to write a patch, it seems.

A one-line patch, I guess, PyFile_CheckExact instead of PyFile_Check. Or a
few lines, checking if the write method is still the builtin one. As this
is the third time I see this question I'll try to submit the patch.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top