-2
class S:
    def __init__(self):
        sess.do_something()

Main:

if __name__ == '__main__':
    with Session() as sess:
        s1 = S()
        s1.do_something()

The above code works as long as class S is in the same file. It doesn't work (NameError: name 'sess' is not defined) when class is in a separate file.

Is this expected?

Danijel
  • 8,198
  • 18
  • 69
  • 133
  • 5
    Yes, that's quite expected. It doesn't have anything to do with `with`. You can simply look at the file in which `S` is defined. Is `sess` defined or imported in it in any way? No? Then it doesn't exist. – deceze Oct 22 '19 at 13:36
  • Use ```import``` if it is in another file. [Like Here](https://stackoverflow.com/questions/4142151/how-to-import-the-class-within-the-same-directory-or-sub-directory) – OneCrazyGenius Oct 22 '19 at 13:37
  • this how method handle search for reference, in your case: search in it's scope first, the scope of class second, the scope of module. – Charif DZ Oct 22 '19 at 13:39
  • `with` does not provide additional scope. it calls e.g. clean-up method on the referred object (`sess`) in your case. check e.g. [this](https://stackoverflow.com/a/3012921/10197418) post. – FObersteiner Oct 22 '19 at 13:46
  • @deceze Please add the comment as answer. – Danijel Oct 22 '19 at 13:58
  • https://stackoverflow.com/a/58450423/476 would do, good enough to be a duplicate…? – deceze Oct 22 '19 at 14:03

1 Answers1

0

The problem you are experiencing has nothing to do with the with statement. You have simply created a class in the wrong way. If you want to use the do_something() method of Session() in your class, you can either inherit from it: class S(Session): ..., or you can pass sess as a variable:

class S:
    def __init__(self, session):
        self.session = session

    def do_something(self)
        return self.session.do_something()


if __name__ == '__main__':
    with Session() as sess:
        s1 = S(sess)
        s1.do_something()
alec_djinn
  • 10,104
  • 8
  • 46
  • 71