Python Context Managers and the "with" Statement (__enter__ & __exit__)

  Рет қаралды 70,387

Real Python

Real Python

Күн бұрын

Пікірлер: 71
@zoeyschlemper7486
@zoeyschlemper7486 5 жыл бұрын
This tutorial helped me, thanks! I couldn't grasp how Python just KNOWS that it should "open" and "close" the file, especially if it just KNOWS how to do these entry and exit functions for any other command that "with" is compatible with. I finally got it. In the file() example, file.open and file.close are versions of the generalized functions of "__enter__" and "__exit__," which are functions that exist in all sorts of python modules. "with" works by doing the "__enter__" and "__exit__" functions automatically. I feel like all the other tutorials I tried before this could start by saying that single sentence and everyone would say "Ohhhh".
@Anutechtrwebgodz
@Anutechtrwebgodz 5 жыл бұрын
2019 still best explanation on the web.
@zolika154
@zolika154 4 жыл бұрын
2020, same is true
@محمدالزعبي-ن9ظ
@محمدالزعبي-ن9ظ 3 жыл бұрын
2021 and still
@DanielSaldivarSalas
@DanielSaldivarSalas 6 жыл бұрын
This is the best god damn video on the "with" statement I have ever seen.
@realpython
@realpython 6 жыл бұрын
Thanks! I'm glad you enjoyed it.
@jvsonyt
@jvsonyt 4 жыл бұрын
This saved me a whole line of code, and for that I'm grateful
@joshuarudd6297
@joshuarudd6297 3 жыл бұрын
2021 still the best explanation on the web.
@narasimhamurthy4791
@narasimhamurthy4791 5 жыл бұрын
Randomly I ended up here found this too good. Now I am gonna watch all of these.
@realpython
@realpython 5 жыл бұрын
I'm glad you enjoyed the video!
@Gruuvin1
@Gruuvin1 3 жыл бұрын
I am now going to write context managed classes for connection objects. Love this! Note: one can write code to open a file, then read/write a file, but may or may not remember to close the file, and even if they do close the file, it's less likely to be done in a 'finally:' clause, so there is no guarantee it will be closed. The point is, try/finally wouldn't even get used for open/close (because people can write bad code, and it still seems to 'work'). This is why we have a context manager: to make python play nice with the OS. Also, I think the contextmanager decorator code communicates what it is better than the class code, even to someone who may not well understand decorators and generators.
@kmarchis
@kmarchis 5 жыл бұрын
really excellent. one of the clearest technical explanations i've seen
@produdeyay
@produdeyay 4 жыл бұрын
17 March 2020 - One word, Amazing and thanks!
@lawrencedoliveiro9104
@lawrencedoliveiro9104 6 жыл бұрын
2:58 The important reason for calling close() (or flush()) on an *output* file is so that you catch any I/O errors on the writes. Otherwise you could suffer loss of data without realizing it! Consider this littie script: f = open("/dev/full", "w") f.write("junk") That should raise “OSError: [Errno 28] No space left on device”, but because the script exits before the file is properly closed, you never see that. This version, on the other hand with open("/dev/full", "w") as f : f.write("junk") #end with does properly raise the error. As does f = open("/dev/full", "w") f.write("junk") f.close() but the with-statement version guarantees to flush the output even if some exception occurs before getting to the end.
@toastrecon
@toastrecon 5 жыл бұрын
I was just wondering about this the other day. Super clear explanation. Thanks!
@realpython
@realpython 5 жыл бұрын
You're welcome!
@EmanuelRamneantu
@EmanuelRamneantu 4 жыл бұрын
Great explanation, with the user defined class and all. Thank you!
@filosofiadetalhista
@filosofiadetalhista 4 жыл бұрын
Wow, I'm really thankful for your explanation!
@hardcode2174
@hardcode2174 4 жыл бұрын
Nicely explained sir. I'm ur new subscriber. Thanks a lot for this vedio.
@maryguty1705
@maryguty1705 3 жыл бұрын
how do you get terminal code prompts and suggestions like in the video? could it do that on pycharm terminal and console?
@brianaragon1641
@brianaragon1641 4 жыл бұрын
Excellent!!! Nice and clear
@xmingw
@xmingw 4 жыл бұрын
Which REPL are you using in the video? It looks awesome, is it ptpython?
@kcvinu
@kcvinu 2 жыл бұрын
Really helpful. Thanks for the video. One question. Is there any performance loss in this approach ?
@kotik1221
@kotik1221 7 жыл бұрын
I believe you should put the line where you open the file outside of the try statement. Otherwise, if the file doesn't exist, an error is raised, and in addition in finally you call the close on the file handler var which wasn't created. As a result, 2 errors raised.
@realpython
@realpython 7 жыл бұрын
Thanks for sharing your thoughts on this!
@republic8360
@republic8360 7 жыл бұрын
This is way more helpful than the stack overflow page. Thanks
@realpython
@realpython 7 жыл бұрын
Cheers, it makes me really happy to hear that :-)
@lawrencedoliveiro9104
@lawrencedoliveiro9104 6 жыл бұрын
3:33 Really the only situation where you could leak resources is when you are accessing some low-level API, for example via ctypes. In this case the calls you are making are equivalent to what you would do in a lower-level language like C, where you have to explicitly allocate and free all dynamic resources. The best thing to do in this situation is to create a Python wrapper for the lower-level C API, so the objects implemented by that API are represented by high-level Python objects that automatically manage their own resources just like any other Python object. In the wrapper you might use with-statements, try-finally blocks, and of course the __del__ method for making sure the lower-level resource-freeing calls are invoked before the Python object disappears.
@zes7215
@zes7215 6 жыл бұрын
no such thing as ideal or enough or not, any is ok, no such thing as easy or not lifex, ts just toolx doesn't matter. ts not communicx or not
@maryguty1705
@maryguty1705 3 жыл бұрын
yield versus return. what is the difference?
@imyashkale
@imyashkale 4 жыл бұрын
which code editor is this??
@basikattack3900
@basikattack3900 5 жыл бұрын
What do you mean by "leak resources" by not using with?
@ahp-6785
@ahp-6785 9 ай бұрын
probably it's incorrect that after with statement the object closes. Because when we use "with tensorflow.GradientTape() as tape:" we use tape even beyond the with statement.
@igoorsimoess
@igoorsimoess 2 жыл бұрын
tks, it helps a lot
@MrScX
@MrScX 7 жыл бұрын
Hi, thank you very much. Your videos are really helpful. Well explained! Kudos to you.
@realpython
@realpython 7 жыл бұрын
Thanks Mushfiqur, I really appreciate it! Happy Pythoning!
@Qasim.Alameri
@Qasim.Alameri 3 жыл бұрын
Thanks bro
@landro3552
@landro3552 5 жыл бұрын
In my case, the program sometimes RANDOMLY outputs the keys with the ASCII table form. Ex: "\x08" pressed sometimes it works ok. anyone knows why
@danielmbicalho
@danielmbicalho 7 жыл бұрын
Great man. Like your vdeos so much. Help me a lot
@kebman
@kebman 4 жыл бұрын
with explaind as very return well # (It's very pythonic!)
@sowellmemo
@sowellmemo 4 жыл бұрын
Very interesting! I got a little confused on the last example though xD Is not the decorator already closing the file, making the f.close() inside managed_file function a little redundant?
@krishj8011
@krishj8011 4 жыл бұрын
Thanks...
@dancordoba7777
@dancordoba7777 2 жыл бұрын
thanks!
@Gigolas88
@Gigolas88 5 жыл бұрын
Nice video, thanks!
@realpython
@realpython 5 жыл бұрын
You're welcome!
@srikanthvattukuti1131
@srikanthvattukuti1131 7 жыл бұрын
why '',' operator using in the assignment like d,=4 or return d,
@mattc41190
@mattc41190 7 жыл бұрын
Beautifully done. Do the mugs on your site support you?
@realpython
@realpython 7 жыл бұрын
Thank you! Yes, the mugs do help support me, they are also great for some unique Python Swag! :-)
@jerfersonmatos28
@jerfersonmatos28 7 жыл бұрын
I'm not native, what's a swag? And what's mug in the context you're referring to
@mattc41190
@mattc41190 7 жыл бұрын
nerdlettering.com/?ref=dbaderorg
@slowsnail2389
@slowsnail2389 5 жыл бұрын
Could you please tell me how the ,, exit file " would work after that I have written "printed" an output to a text file ? Thanks in forward :)
@kebman
@kebman 4 жыл бұрын
It releases the handle to the garbage collection heap, so the memory is free again. FREEDOM!
@stm5275
@stm5275 4 жыл бұрын
What is the point of "f"?
@hungngv935
@hungngv935 6 жыл бұрын
Thank you so much!
@realpython
@realpython 6 жыл бұрын
You're welcome!
@382946rthu
@382946rthu 7 жыл бұрын
I enjoy your videos and I will be looking for your book(s).
@mariuswirtz4427
@mariuswirtz4427 7 жыл бұрын
Hi Dan, do you plan to release a printed version of your book in the future?
@mariuswirtz4427
@mariuswirtz4427 7 жыл бұрын
Thanks!
@lawrencedoliveiro9104
@lawrencedoliveiro9104 6 жыл бұрын
2:27 That’s not a reason for using a with-statement. Remember that *all* Python objects keep track of their resources anyway, and free them when they disappear. And CPython is reference-counted, so this happens immediately the last reference to an object goes away.
@manishjain6294
@manishjain6294 5 жыл бұрын
This video stucks after few seconds. Doesn't move after about 40sec. Kindly upload again.
@realpython
@realpython 5 жыл бұрын
The video appears to be working fine on our end, are you able to try another web browser? This may resolve the problem.
@manishjain6294
@manishjain6294 5 жыл бұрын
Hello Dan. Thanks for replying. It's is playing smoothly.
@licensetothrill
@licensetothrill 6 жыл бұрын
Noob question -- can I use my own function in the statement and it operates normally? Like, def my_function( ): complex junk here with open('file') as fileObj: my_function( )
@hunters.dicicco1410
@hunters.dicicco1410 6 жыл бұрын
in this case, what purpose does opening the file serve? calling open('file') is effectively checking whether the file exists, yielding it and closing it without changing it. unless the "complex junk" manipulates said file, which opens another can of worms where the file is referenced before it is opened, let alone that my_function takes no parameters and thus *cannot* know what file you're referring to.
@kebman
@kebman 4 жыл бұрын
The only generators I like, are those who generate money........
@Bengadeer
@Bengadeer 4 жыл бұрын
Maybe you should close the video by saying: "Use the 'with open' syntax to optimize your file opening code realizing what's going on structurally within python"
@kevinriordan188
@kevinriordan188 3 жыл бұрын
with Much(love): me.thank(you)
@poorgirl9458
@poorgirl9458 5 жыл бұрын
What is it exactly that highlights syntax in your python console? I see this is explained in your other video clip: m.kzbin.info/www/bejne/mZjCZHhpeMdmg6M Thank you for both! You’re a star!
@ThuyTrang-ml6ej
@ThuyTrang-ml6ej 2 жыл бұрын
the video image is too poor, you need to fix it more
@lukeav6097
@lukeav6097 2 жыл бұрын
OMG, use an IDE for crying out loud
Installing Python Packages with pip and virtualenv / venv
8:42
Real Python
Рет қаралды 55 М.
Python Tutorial: Context Managers - Efficiently Managing Resources
20:37
PRANK😂 rate Mark’s kick 1-10 🤕
00:14
Diana Belitskay
Рет қаралды 9 МЛН
СОБАКА ВЕРНУЛА ТАБАЛАПКИ😱#shorts
00:25
INNA SERG
Рет қаралды 3,6 МЛН
Who's spending her birthday with Harley Quinn on halloween?#Harley Quinn #joker
01:00
Harley Quinn with the Joker
Рет қаралды 23 МЛН
Optional Arguments in Python With *args and **kwargs
10:44
Real Python
Рет қаралды 125 М.
String Conversion in Python: When to Use __repr__ vs __str__
14:58
Python Decorators: The Secret to Supercharging Your Code
20:53
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 120 М.
Python dataclasses will save you HOURS, also featuring attrs
8:50
Python Function Argument Unpacking Tutorial (* and ** Operators)
9:42
Python Tutorial: Unit Testing Your Code with the unittest Module
39:13
Corey Schafer
Рет қаралды 1,3 МЛН
JAVA DTO Pattern Tutorial | Simplify Your Code
19:12
Amigoscode
Рет қаралды 212 М.
PRANK😂 rate Mark’s kick 1-10 🤕
00:14
Diana Belitskay
Рет қаралды 9 МЛН