4

I am using a session as an attribute of my class, as in

self.sess = tf.Session()

or

self.sess = tf.InteractiveSession()

The session attribute is used in several functions, e.g.

def get_loss(self, input_data):
        return self.sess.run(self.loss, {self.data:input_data})

I know that a session has to be closed at some point. Does this also apply when using the session as an attribute of a class? Do I need a "close_session" function somewhere? If yes, where exactly should I put it in the class?

Regrettably, I couldn't find anything on sessions as class attributes so I am thankful for any advice.

Lemon
  • 1,394
  • 3
  • 14
  • 24

1 Answers1

2

You should implement a close() or __exit__() member function that calls self.sess.close(). Then use your object as you would do with a Session:

with MyClass() as myobj:
    ...

EDIT (increased verbosity level)

Regarding python's with statement, its usefulness and how to build compatible classes, there are plenty of resources out there. Its use is basically to neatly handle the life cycle of the resources of an object.

A clean way to use a context manager (an object usually handled with a with statement) as a member function of a class is to make that class a context manager itself.

If you simply open a Session context within a member function of your object, then the effective lifespan of this object (of its resources anyway) ends with the with block: in effect, this session object is not a class member but simply a local variable of the function. If you want to use the same Session in several member functions of your class, you need to extend the lifetime of the Session resources beyond a single function and let the resources be handles by your class by letting it be a context manager.

P-Gn
  • 23,115
  • 9
  • 87
  • 104
  • At what time should I call the sess.close() function? – Lemon Jun 21 '17 at 09:41
  • `Session.close()` is be called when `MyClass.close()` is called, and if you follow the idiom above, that will be called when the `with` scope is closed. In short, do not call them by hand but let scopes take care of it. – P-Gn Jun 21 '17 at 10:53
  • Sorry but I'm still not sure whether I understand what you mean. When I initialize an instance of the class, like instance = MyClass(params) how should I use it with a with scope? And how is MyClass.close() automatically called in your with scope? Could you maybe provide a link showing this construction in practice? – Lemon Jun 27 '17 at 07:12
  • Wouldn't it rather make sense to use "with instance.session as sess:" after initializing a member of the class? Also, I would have to change all my functions in the class, correct? Right now, as shown in the original post, a class returns e.g. "self.sess.run(self.loss, ...)" – Lemon Jun 27 '17 at 07:15