4

I've recently started to learn python , and I reached the with statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code :


from __future__ import with_statement
import pdb

class Geo:

  def __init__(self,text):
    self.text = text

  def __enter__(self):
    print "entering"

  def __exit__(self,exception_type,exception_value,exception_traceback):
    print "exiting"

  def ok(self):
    print self.text

  def __get(self):
    return self.text


with Geo("line") as g :
  g.ok()

The thing is that when the interpreter reaches the ok method inside the with statement , the following exception is raised :


Traceback (most recent call last):
  File "dec.py", line 23, in 
    g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'

Why does the g object have the type NoneType ? How can I use an instance with the with statement ?

1 Answer 1

12

Your __enter__ method needs to return the object that should be used for the "as g" part of the with statement. See the documentation, where it states:

  • If a target was included in the with statement, the return value from __enter__() is assigned to it.

Currently, it has no return statement, so g gets bound to None (the default return value)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.