Hack Forums
[Python] Context Managers - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Context Managers (/showthread.php?tid=5557139)



Context Managers - (╯°□°)╯︵ ┻━━┻ - Feb 21, 2017


[Image: hJCWljW.png]
[Image: y4XuedU.png]
[Image: a8DAjI9.png]
[Image: PcUlOcU.png]
[Image: 4hBJ51C.png]

I'm not a fan of the way HF formats code so I'm going to be posting pictures. Click the link at the top for the code itself.

I have a few more tutorials planned, let me know if you guys want anything specific.


* - Goodies - Feb 21, 2017

Nice! Too many people on here don't use context managers, and then they mess up their try/finally blocks.

It should also be noted that, while Python 2.7 does not have built in support for certain context managers (primarily sockets), you can (and should) use the contextlib module.

PHP Code

<?php 
#!/usr/bin/env python3
import socket
with socket
.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    
sock.connect(("7.7.7.7", 80)) 

This will work in Python3, but will not in Python2. Generally, what you do is this:

PHP Code

<?php 
#!/usr/bin/env python2
import socket

sock 
= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    
sock.connect(("7.7.7.7", 80))
finally:
    
sock.close() 

Equivalently, you can use contextlib's "closing" wrapper:
PHP Code

<?php 
#!/usr/bin/env python2
import socket
from contextlib import closing
with closing
(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
    
sock.connect(("7.7.7.7", 80)) 

etc...

But yes, context managers are just classes that have the_enter_ and_exit_ functions defined. That timer is actually pretty nifty, although I usually just use a decorator.


* - (╯°□°)╯︵ ┻━━┻ - Feb 21, 2017

(Feb 21, 2017 12:18 PM)Goodies Wrote:  -snip-

I didn't know that since I don't work with sockets but I've seen a few other people use them on here. Thanks!


* - Goodies - Feb 21, 2017

(Feb 21, 2017 12:47 PM)(╯°□°)╯︵ ┻━━┻ Wrote:  I didn't know that since I don't work with sockets but I've seen a few other people use them on here. Thanks!

Yeah! Context managers are about as close as we can get to constructors/destructors.