Тёмный

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

Real Python
Подписаться 193 тыс.
Просмотров 70 тыс.
50% 1

Опубликовано:

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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".
@jvsonyt
@jvsonyt 4 года назад
This saved me a whole line of code, and for that I'm grateful
@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.
@xmingw
@xmingw 4 года назад
Which REPL are you using in the video? It looks awesome, is it ptpython?
@produdeyay
@produdeyay 4 года назад
17 March 2020 - One word, Amazing and thanks!
@ahp-6785
@ahp-6785 7 месяцев назад
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.
@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?
@kebman
@kebman 4 года назад
with explaind as very return well # (It's very pythonic!)
@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!
@kebman
@kebman 4 года назад
The only generators I like, are those who generate money........
@kmarchis
@kmarchis 5 лет назад
really excellent. one of the clearest technical explanations i've seen
@maryguty1705
@maryguty1705 3 года назад
yield versus return. what is the difference?
@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!
@imyashkale
@imyashkale 3 года назад
which code editor is this??
@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!
@kcvinu
@kcvinu Год назад
Really helpful. Thanks for the video. One question. Is there any performance loss in this approach ?
@stm5275
@stm5275 4 года назад
What is the point of "f"?
@igoorsimoess
@igoorsimoess 2 года назад
tks, it helps a lot
@hardcode2174
@hardcode2174 4 года назад
Nicely explained sir. I'm ur new subscriber. Thanks a lot for this vedio.
@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"
@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
@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
@Qasim.Alameri
@Qasim.Alameri 3 года назад
Thanks bro
@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.ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-cg_3E3Cb3MA.html Thank you for both! You’re a star!
@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.
@basikattack3900
@basikattack3900 5 лет назад
What do you mean by "leak resources" by not using with?
@joshuarudd6297
@joshuarudd6297 3 года назад
2021 still the best explanation on the web.
@dancordoba7777
@dancordoba7777 2 года назад
thanks!
@krishj8011
@krishj8011 4 года назад
Thanks...
@hoegge
@hoegge 9 месяцев назад
Using yield does not make it a generator, but is just a "hack" to keep the local state active
@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?
@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.
@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.
@filosofiadetalhista
@filosofiadetalhista 4 года назад
Wow, I'm really thankful for your explanation!
@srikanthvattukuti1131
@srikanthvattukuti1131 7 лет назад
why '',' operator using in the assignment like d,=4 or return d,
@EmanuelRamneantu
@EmanuelRamneantu 3 года назад
Great explanation, with the user defined class and all. Thank you!
@danielmbicalho
@danielmbicalho 7 лет назад
Great man. Like your vdeos so much. Help me a lot
@382946rthu
@382946rthu 7 лет назад
I enjoy your videos and I will be looking for your book(s).
@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.
@brianaragon1641
@brianaragon1641 4 года назад
Excellent!!! Nice and clear
@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
@toastrecon
@toastrecon 5 лет назад
I was just wondering about this the other day. Super clear explanation. Thanks!
@realpython
@realpython 5 лет назад
You're welcome!
@mariuswirtz4427
@mariuswirtz4427 7 лет назад
Hi Dan, do you plan to release a printed version of your book in the future?
@mariuswirtz4427
@mariuswirtz4427 7 лет назад
Thanks!
@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!
@Gigolas88
@Gigolas88 5 лет назад
Nice video, thanks!
@realpython
@realpython 5 лет назад
You're welcome!
@hungngv935
@hungngv935 6 лет назад
Thank you so much!
@realpython
@realpython 6 лет назад
You're welcome!
@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 :-)
@kevinriordan188
@kevinriordan188 3 года назад
with Much(love): me.thank(you)
@lukeav6097
@lukeav6097 2 года назад
OMG, use an IDE for crying out loud
@ThuyTrang-ml6ej
@ThuyTrang-ml6ej 2 года назад
the video image is too poor, you need to fix it more
@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.
Далее
Optional Arguments in Python With *args and **kwargs
10:44
Почему?
00:22
Просмотров 283 тыс.
ОБЗОР НА ШТАНЫ от БЕЗДNA
00:59
Просмотров 355 тыс.
PLEASE Use These 5 Python Decorators
20:12
Просмотров 113 тыс.
Expert Python Tutorial #6 - Context Managers
16:38
Просмотров 70 тыс.
8 things in Python you didn't realize are descriptors
14:21
Pytest Tutorial - How to Test Python Code
1:28:39
Просмотров 198 тыс.