What is the difference between init and enter?

Ken Seehart ken at seehart.com
Tue May 26 15:14:34 CEST 2009

Diez B. Roggisch wrote:
> John wrote:
>> I'm okay with init, but it seems to me that enter is redundant since it
>> appears that anything you want to execute in enter can be done in init.
> About what are you talking? 
> Diez
Presumably, the 'with' statement.  http://www.python.org/dev/peps/pep-0343/


    Enter the runtime context related to this object. The *with*
    <http://effbot.org/pyref/with.htm> statement will bind this method's
    return value to the target(s) specified in the *as*
    <http://effbot.org/pyref/as.htm> clause of the statement, if any.

Unlike __init__,  __enter__ can return a value, which is assigned to the 
variable (or tuple) following the 'as' keyword:

        with EXPR as VAR:

Also, the object used in a with statement can be constructed prior to 
the with statement.  The __init__ method is called when the object is 
initialized, but the __enter__ method is called when the context is 
entered (i.e. when the 'with' statement is invoked).


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090526/5e2d4b95/attachment.html>

More information about the Python-list mailing list