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 3354602
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T02:17:35+00:00 2026-05-18T02:17:35+00:00

I would like to create a class that describes a file resource and then

  • 0

I would like to create a class that describes a file resource and then pickle it. This part is straightforward. To be concrete, let’s say that I have a class “A” that has methods to operate on a file. I can pickle this object if it does not contain a file handle. I want to be able to create a file handle in order to access the resource described by “A”. If I have an “open()” method in class “A” that opens and stores the file handle for later use, then “A” is no longer pickleable. (I add here that opening the file includes some non-trivial indexing which cannot be cached–third party code–so closing and reopening when needed is not without expense). I could code class “A” as a factory that can generate file handles to the described file, but that could result in multiple file handles accessing the file contents simultaneously. I could use another class “B” to handle the opening of the file in class “A”, including locking, etc. I am probably overthinking this, but any hints would be appreciated.

  • 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-05-18T02:17:35+00:00Added an answer on May 18, 2026 at 2:17 am

    The question isn’t too clear; what it looks like is that:

    • you have a third-party module which has picklable classes
    • those classes may contain references to files, which makes the classes themselves not picklable because open files aren’t picklable.

    Essentially, you want to make open files picklable. You can do this fairly easily, with certain caveats. Here’s an incomplete but functional sample:

    import pickle
    class PicklableFile(object):
        def __init__(self, fileobj):
            self.fileobj = fileobj
    
        def __getattr__(self, key):
            return getattr(self.fileobj, key)
    
        def __getstate__(self):
            ret = self.__dict__.copy()
            ret['_file_name'] = self.fileobj.name
            ret['_file_mode'] = self.fileobj.mode
            ret['_file_pos'] = self.fileobj.tell()
            del ret['fileobj']
            return ret
    
        def __setstate__(self, dict):
            self.fileobj = open(dict['_file_name'], dict['_file_mode'])
            self.fileobj.seek(dict['_file_pos'])
            del dict['_file_name']
            del dict['_file_mode']
            del dict['_file_pos']
            self.__dict__.update(dict)
    
    f = PicklableFile(open("/tmp/blah"))
    print f.readline()
    data = pickle.dumps(f)
    f2 = pickle.loads(data)
    print f2.read()
    

    Caveats and notes, some obvious, some less so:

    • This class should operate directly on the file object you got from open. If you’re using wrapper classes on files, like gzip.GzipFile, those should go above this, not below it. Logically, treat this as a decorator class on top of file.
    • If the file doesn’t exist when you unpickle, it can’t be unpickled and will throw an exception.
    • If it’s a different file, the behavior may or may not make sense.
    • If the file mode includes file creation (‘w+’), and the file doesn’t exist, it’ll be created; we don’t know what file permissions to use, since that’s not stored with the file. If this is important–it probably shouldn’t be–then store the correct permissions in the class when you first create it.
    • If the file isn’t seekable, trying to seek to the old position may raise IOError; if you’re using a file like that you’ll need to decide how to handle that.
    • The file classes in Python 2 and Python 3 are different; there’s no file class in Python 3. Even if you’re only using Python 2 right now, don’t subclass file.

    I’d steer away from doing this; having pickled data dependent on external files not changing and staying in the same place is brittle. This makes it difficult to even relocate files, since your pickled data won’t make sense.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to create a class that creates and manages log files. I
I would like create my own collection that has all the attributes of python
I would like create a web service in ASP.Net 2.0 that will supports JSON.
I would like to create a file format for my app like Quake, OO,
I would like to create a stored procedure in MySQL that took a list
I would like to create events for certain resources that are used across various
Would like to create a strong password in C++. Any suggestions? I assume it
I would like to create a database backed interactive AJAX webapp which has a
I would like to create an SSL connection for generic TCP communication. I think
I would like to create an application wide keyboard shortcut for a Java Swing

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.