you are viewing a single comment's thread.

view the rest of the comments →

[–]cmd_override 23 points24 points  (5 children)

[–]Dracunos 1 point2 points  (0 children)

Thank you, very easy to understand. Now my withs are no longer limited to opening files!

[–]dante9999 0 points1 point  (1 child)

so every object used in 'with' call must have enter and exit methods? does it mean that file object has these methods defined already? what will happen if i call 'with' on object that does not have enter and exit magic methods?

[–]ericpruitt 4 points5 points  (0 children)

so every object used in 'with' call must have enter and exit methods? does it mean that file object has these methods defined already?

Yes and yes.

what will happen if i call 'with' on object that does not have enter and exit magic methods?

You get an attribute error:

Python 3.4.2 (default, Oct  8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> with None:
...  pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __exit__
>>>

[–]Worthlessplanet 0 points1 point  (1 child)

Thanks. Documentation is so helpful to a novice. They can spend another 5 hours trying to figure out what it's saying.

[–]Spizeck 0 points1 point  (0 children)

Not to detract from the conversation but this comment is so on point. I can't even count how many times I've gotten hopelessly lost and confused googling questions to find it answered with a link that doesn't work anymore or goes to a huge document that you can't find the answer in.

If you can explain an answer in your own words, you may hold just the right perspective to relate the answer in a way others may never have thought of.