What does the "with" keyword do in python?

Put your programming skills to the test in these challenges.

What does the "with" keyword do in python?

Post by ghostheadx2 on Fri Apr 10, 2015 9:09 pm
([msg=87666]see What does the "with" keyword do in python?[/msg])

I found a question at this link and couldn't understand the answer:

http://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for

Could someone please explain to me what the "with" keyword does in python in simpler terms? Thanks.

Best,

ghostheadx2

-- Fri Apr 10, 2015 9:35 pm --

I also could use some help explaining the "in" keyword. I know what it means but its hard to explain. The explanation I found is here if you ctrl-F "in keyword" on this page:

http://zetcode.com/lang/python/keywords/
ghostheadx2
Contributor
Contributor
 
Posts: 728
Joined: Wed Nov 19, 2014 1:19 am
Blog: View Blog (0)


Re: What does the "with" keyword do in python?

Post by ghost107 on Sun Apr 12, 2015 8:47 am
([msg=87668]see Re: What does the "with" keyword do in python?[/msg])

with:
Python uses a garbage collector to collect and destroy objects that are created, there are also objects that needs to be destroyed manually, to free up memory(those objects use unmanaged resources).
Code: Select all
1:f = open("x.txt") #opening the stream for  f
2:data = f.read() 
  # ...
n:f.close() #closing the stream for f

If something happens with the application between lines 1 to n the stream will remain open.

A solution would be:
Code: Select all
1:try:
2:   f = open("file", "r")  #opening the stream for  f
3:   data = f.read()   
     # ...
n:finally:
   f.close()   #closing the stream for f

If anything happens to the application, it will close the stream. Another solution is using the "with" statement("with" is the same as the code above without writing try-finally, and f.close()).

The objects created with "with", are automatically destroyed when exiting the with code section. For example lets say you access some native C/C++ code with python, and you have to destroy those objects, you can destroy the objects manually, or creating objects with "with"

Code: Select all
with open("text.txt") as f:   #opening the stream for  f
    data = f.read()
    # ...
#closing the stream for f


in:
If it is used as a condition("in" and "not in"), it will check if the object you are mentioning is part or not part of the collection.
Code: Select all
#!/usr/bin/python

# grades.py

grades = ["A", "B", "C", "D", "E", "F"]

grade = "L"

if grade not in grades:
   print "unknown grade"


if it is used to iterate elements from a collection(like a for loop), The object used will iterate each element from that collection
Code: Select all
for grade in grades :
   print grade
User avatar
ghost107
Poster
Poster
 
Posts: 321
Joined: Wed Jul 02, 2008 7:57 am
Blog: View Blog (0)


Re: What does the "with" keyword do in python?

Post by ghostheadx2 on Mon Apr 13, 2015 1:52 pm
([msg=87679]see Re: What does the "with" keyword do in python?[/msg])

ghost107 wrote:with:
Python uses a garbage collector to collect and destroy objects that are created, there are also objects that needs to be destroyed manually, to free up memory(those objects use unmanaged resources).
Code: Select all
1:f = open("x.txt") #opening the stream for  f
2:data = f.read() 
  # ...
n:f.close() #closing the stream for f

If something happens with the application between lines 1 to n the stream will remain open.

A solution would be:
Code: Select all
1:try:
2:   f = open("file", "r")  #opening the stream for  f
3:   data = f.read()   
     # ...
n:finally:
   f.close()   #closing the stream for f

If anything happens to the application, it will close the stream. Another solution is using the "with" statement("with" is the same as the code above without writing try-finally, and f.close()).

The objects created with "with", are automatically destroyed when exiting the with code section. For example lets say you access some native C/C++ code with python, and you have to destroy those objects, you can destroy the objects manually, or creating objects with "with"

Code: Select all
with open("text.txt") as f:   #opening the stream for  f
    data = f.read()
    # ...
#closing the stream for f


in:
If it is used as a condition("in" and "not in"), it will check if the object you are mentioning is part or not part of the collection.
Code: Select all
#!/usr/bin/python

# grades.py

grades = ["A", "B", "C", "D", "E", "F"]

grade = "L"

if grade not in grades:
   print "unknown grade"


if it is used to iterate elements from a collection(like a for loop), The object used will iterate each element from that collection
Code: Select all
for grade in grades :
   print grade


That's all great but only the third example uses with. I get that its used instead of try-finally, but also could you explain the concept of try-finally better. Also, could you walk me through some more examples of "with" or "try-finally" because not every example you've given has the term "with" and I know its relevant but I don't see the resemblance.

I get what this means when you quoted it:

Code: Select all
y = [1, 2, 3, 4, 5]

for x in y:
  print x


That I completely understood when you wrote it, but not your explanation on its resemblance or relevance to "with." I think it means this:

"with" immediately creates new objects, then gets rid of them. Try creates objects and after the "finally" statement they are destroyed. "with" somehow does this in one statement.

Where in the "with" statement is it destroyed? Like, what's the whole process?
ghostheadx2
Contributor
Contributor
 
Posts: 728
Joined: Wed Nov 19, 2014 1:19 am
Blog: View Blog (0)


Re: What does the "with" keyword do in python?

Post by Iblist on Mon Apr 13, 2015 3:37 pm
([msg=87680]see Re: What does the "with" keyword do in python?[/msg])

A with statement starts by creating an object, those objects exist while the block of code pertaining to the with statement is run, and are then destroyed upon exiting the block of code.

Code: Select all
with open("file.txt") as FILE: << The object FILE is created, it is a pointer to the file 'file.txt'
    data = FILE.read()                     << Fun stuff is done with FILE
    do something with data              << something is done with data
#END OF BLOCK#                       << The object FILE is now destroyed.


Basically, the object created by the with statement (in this case FILE) exists as long as it is needed and destroyed immediately afterwards cleanly and safely.
Those who create and rely upon brilliant and complex creations are often destroyed by some idiot plugging an infected usb stick somewhere they shouldn't have.
User avatar
Iblist
Experienced User
Experienced User
 
Posts: 68
Joined: Fri Jul 11, 2014 12:05 pm
Blog: View Blog (0)


Re: What does the "with" keyword do in python?

Post by ghostheadx2 on Mon Apr 13, 2015 4:47 pm
([msg=87682]see Re: What does the "with" keyword do in python?[/msg])

Thanks IbList, that explanation works perfectly.
ghostheadx2
Contributor
Contributor
 
Posts: 728
Joined: Wed Nov 19, 2014 1:19 am
Blog: View Blog (0)



Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests