Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8601983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T01:58:14+00:00 2026-06-12T01:58:14+00:00

I wanted a file object that flushes out straight to file as data is

  • 0

I wanted a file object that flushes out straight to file as data is being written, and wrote this:

class FlushingFileObject(file):
    def write(self,*args,**kwargs):
        return_val= file.write(self,*args,**kwargs)
        self.flush()
        return return_val

    def writelines(self,*args,**kwargs):
        return_val= file.writelines(self,*args,**kwargs)
        self.flush()
        return return_val

but interestingly it doesn’t flush as I write to it, so I tried a few things including this:

class FlushingFileObject(object):
    def __init__(self,*args,**kwargs):
        self.file_object= file(*args,**kwargs)

    def __getattr__(self, item):
        return getattr(self.file_object,item)

    def write(self,*args,**kwargs):
        return_val= self.file_object.write(*args,**kwargs)
        self.file_object.flush()
        return return_val

    def writelines(self,*args,**kwargs):
        return_val= self.file_object.writelines(*args,**kwargs)
        self.file_object.flush()
        return return_val

which does flush.

Why doesn’t subclassing file work in this instance?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T01:58:15+00:00Added an answer on June 12, 2026 at 1:58 am

    Great question.

    This happens because Python optimizes calls to write on file objects by bypassing the Python-level write method and calling fputs directly.

    To see this in action, consider:

    $ cat file_subclass.py
    import sys
    class FileSubclass(file):
        def write(self, *a, **kw):
            raise Exception("write called!")
        writelines = write
    sys.stdout = FileSubclass("/dev/null", "w")
    print "foo"
    sys.stderr.write("print succeeded!\n")
    $ python print_magic.py
    print succeeded!
    

    The write method was never called!

    Now, when the object isn’t a subclass of file, things work as expected:

    $ cat object_subclass.py
    import sys
    class ObjectSubclass(object):
        def __init__(self):
            pass
        def write(self, *a, **kw):
            raise Exception("write called!")
        writelines = write
    sys.stdout = ObjectSubclass()
    print "foo"
    sys.stderr.write("print succeeded!\n")
    $ python object_subclass.py
    Traceback (most recent call last):
      File "x.py", line 13, in <module>
        print "foo"
      File "x.py", line 8, in write
        raise Exception("write called!")
    Exception: write called!
    

    Digging through the Python source a bit, it looks like the culprit is the PyFile_WriteString function, called by the print statement, which checks to see whether the object being written to is an instance of file, and if it is, bypasses the object’s methods and calls fputs directly:

    int
    PyFile_WriteString(const char *s, PyObject *f)
    {
    
        if (f == NULL) {
            /* … snip … */
        }
        else if (PyFile_Check(f)) { //-- `isinstance(f, file)`
            PyFileObject *fobj = (PyFileObject *) f;
            FILE *fp = PyFile_AsFile(f);
            if (fp == NULL) {
                err_closed();
                return -1;
            }
            FILE_BEGIN_ALLOW_THREADS(fobj)
            fputs(s, fp); //-- fputs, bypassing the Python object entirely
            FILE_END_ALLOW_THREADS(fobj)
            return 0;
        }
        else if (!PyErr_Occurred()) {
            PyObject *v = PyString_FromString(s);
            int err;
            if (v == NULL)
                return -1;
            err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
            Py_DECREF(v);
            return err;
        }
        else
            return -1;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to build an object that looks something like this: public class MyObject
I wanted to extract some data from an SVG file. I know that SVG
I wanted to use find to find every file in a directory that starts
I wanted to parse a text file that contains unstructured text. I need to
I wanted to know what is the maximum size of the file that we
I wanted to write a small script that searched for an exact file name,
This is a question out of curiousity for java or c++, I wanted to
Had an interesting experience with Python's file buffering and wanted to know that I
Before I dive into my question, I wanted to point out that I am
I wanted, to make traversable (by DB, single file or just as string) class

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.