Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

python - Why am I getting "NameError: global name 'open' is not defined" in __del__?

I'm getting a NameError in the __del__ function of a class. I do not understand why 'open' is not accessible inside the function __del__. I am using Python 3.4.0

Python Code:

class Contoller:

    ...

    def __del__(self):
        store = {}
        ...
        pickle.dump(store, open('data.p', 'wb'))    

class MyWindow(Gtk.Window):

    def __init__(self):
        ...
        self.controller = Contoller(self)
        ...
        self.connect("delete-event", self.quit)
        ...

    ...

    def quit(self, widget, event):
        del self.controller
        Gtk.main_quit()

Error Message:

Traceback (most recent call last):
  File "main.py", line 69, in __del__
NameError: name 'open' is not defined
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

user3595184's code used to work until Python 3.4. I know because I've just run into the same issue, calling open() within __del__. Apparently built-in functions no longer work, because of a change in when __del__ is run as the interpreter shuts down.

UPDATE: See https://docs.python.org/3/library/weakref.html, especially the section on finalizers. I have several classes that encapsulate access to resources that had __del__() methods to unlock or clean up as soon as the application would exit, for any reason. Catching all exceptions or exits at the application level and explicitly calling cleanup methods is inconvenient and bug-prone. I'll try using a local finalizer instead.

UPDATE: I'm having better luck with __enter__() and __exit__(), putting the top-level object in a with clause. It appears at least the __exit__() gets called no matter how, so I can call the cleanup methods (__exit__()'s themselves) of all subordinate objects. That's working for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...