Python

What is with clause in Python for? How to use it?

December 21, 2021

What is with clause in Python for? How to use it?

In this article, we’ll learn what the with  clause is in Python, a statement that is used to make code cleaner and more readable.

with clause in Python cover

Hey you programmer, okay? Let’s learn more about Python!

The with statement is used to ensure the completion of acquired resources.

For example: when a file is opened, we can use try and finally, to execute our logic and then close the file

However, some code errors could result in the instruction to close the file not being executed, causing the resources to still be allocated to it.

Therefore, the with instruction was provided, which performs this same operation in a simple way, which guarantees the closure of allocated resources

Let’s see in practice the comparison of both  ideas:

# with try and finally
try:
f = open("teste.txt", "w")
f.write("Testando escrita")
finally:
f.close()

# with clause
with open("teste2.txt", "w") as f:
f.write("Testando escrita com with")

See that using  with we use fewer lines, that is, pythonic code

In addition, we guarantee that the resources to open the file are returned to the machine

The version applying  with makes f.close() unnecessary because of that, at the end of the instruction the file will be closed

Conclusion

In this article, we’ve learned  what is the with clause in Python

The instruction will save us code, observing  that we no longer need to close files

And it works precisely in this sense, to simplify things and return the resources allocated to the machine.

Preventing us from any logic or program errors

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x