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
472 views
in Technique[技术] by (71.8m points)

should the return value for `__enter__` method always be `self` in python

Shouldn't the return value for the __enter__ method be self always.

Python documentation says :

object.__enter__(self) Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

With this, to do anything practical, should't self be returned always from __enter__ method of a class as without it one would not be able to call other class methods on the context.

For example, in the following code, s.main() works fine but b1.main() errors out.

class a(object):
    def __init__(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self ,type, value, traceback):
        return self

    def main(self):
        print " in a::main self %d " , id(self)


class b(object):
    def __init__(self):
        pass

    def __enter__(self):
        return "something else"

    def __exit__(self ,type, value, traceback):
        pass

    def main(self):
        print "in b::main !! self id " , id(self)

with a() as s:
    s.main()

with b() as b1:
    b1.main()

s = a()
s.main()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Not if it makes sense to use an attribute of the instance as the context manager:

class A:
    def __init__(self, useful_obj):
        self.useful_obj = useful_obj

   def __enter__(self):
       return self.useful_obj

   def __exit__(self):
       pass

with A(some_obj) as a:
    # magic done implicitly by a.useful_obj
    .
    .
    .

This situation can be seen in SqlAlchemy's code.

The code sample that you provided would work if you use any of the str methods, for example:

with b() as b1:
    print b1.upper()

>> SOMETHING ELSE

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

...