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".
@Anutechtrwebgodz5 жыл бұрын
2019 still best explanation on the web.
@zolika1544 жыл бұрын
2020, same is true
@محمدالزعبي-ن9ظ3 жыл бұрын
2021 and still
@DanielSaldivarSalas6 жыл бұрын
This is the best god damn video on the "with" statement I have ever seen.
@realpython6 жыл бұрын
Thanks! I'm glad you enjoyed it.
@jvsonyt4 жыл бұрын
This saved me a whole line of code, and for that I'm grateful
@joshuarudd62973 жыл бұрын
2021 still the best explanation on the web.
@narasimhamurthy47915 жыл бұрын
Randomly I ended up here found this too good. Now I am gonna watch all of these.
@realpython5 жыл бұрын
I'm glad you enjoyed the video!
@Gruuvin13 жыл бұрын
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.
@kmarchis5 жыл бұрын
really excellent. one of the clearest technical explanations i've seen
@produdeyay4 жыл бұрын
17 March 2020 - One word, Amazing and thanks!
@lawrencedoliveiro91046 жыл бұрын
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.
@toastrecon5 жыл бұрын
I was just wondering about this the other day. Super clear explanation. Thanks!
@realpython5 жыл бұрын
You're welcome!
@EmanuelRamneantu4 жыл бұрын
Great explanation, with the user defined class and all. Thank you!
@filosofiadetalhista4 жыл бұрын
Wow, I'm really thankful for your explanation!
@hardcode21744 жыл бұрын
Nicely explained sir. I'm ur new subscriber. Thanks a lot for this vedio.
@maryguty17053 жыл бұрын
how do you get terminal code prompts and suggestions like in the video? could it do that on pycharm terminal and console?
@brianaragon16414 жыл бұрын
Excellent!!! Nice and clear
@xmingw4 жыл бұрын
Which REPL are you using in the video? It looks awesome, is it ptpython?
@kcvinu2 жыл бұрын
Really helpful. Thanks for the video. One question. Is there any performance loss in this approach ?
@kotik12217 жыл бұрын
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.
@realpython7 жыл бұрын
Thanks for sharing your thoughts on this!
@republic83607 жыл бұрын
This is way more helpful than the stack overflow page. Thanks
@realpython7 жыл бұрын
Cheers, it makes me really happy to hear that :-)
@lawrencedoliveiro91046 жыл бұрын
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.
@zes72156 жыл бұрын
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
@maryguty17053 жыл бұрын
yield versus return. what is the difference?
@imyashkale4 жыл бұрын
which code editor is this??
@basikattack39005 жыл бұрын
What do you mean by "leak resources" by not using with?
@ahp-67859 ай бұрын
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.
@igoorsimoess2 жыл бұрын
tks, it helps a lot
@MrScX7 жыл бұрын
Hi, thank you very much. Your videos are really helpful. Well explained! Kudos to you.
@realpython7 жыл бұрын
Thanks Mushfiqur, I really appreciate it! Happy Pythoning!
@Qasim.Alameri3 жыл бұрын
Thanks bro
@landro35525 жыл бұрын
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
@danielmbicalho7 жыл бұрын
Great man. Like your vdeos so much. Help me a lot
@kebman4 жыл бұрын
with explaind as very return well # (It's very pythonic!)
@sowellmemo4 жыл бұрын
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?
@krishj80114 жыл бұрын
Thanks...
@dancordoba77772 жыл бұрын
thanks!
@Gigolas885 жыл бұрын
Nice video, thanks!
@realpython5 жыл бұрын
You're welcome!
@srikanthvattukuti11317 жыл бұрын
why '',' operator using in the assignment like d,=4 or return d,
@mattc411907 жыл бұрын
Beautifully done. Do the mugs on your site support you?
@realpython7 жыл бұрын
Thank you! Yes, the mugs do help support me, they are also great for some unique Python Swag! :-)
@jerfersonmatos287 жыл бұрын
I'm not native, what's a swag? And what's mug in the context you're referring to
@mattc411907 жыл бұрын
nerdlettering.com/?ref=dbaderorg
@slowsnail23895 жыл бұрын
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 :)
@kebman4 жыл бұрын
It releases the handle to the garbage collection heap, so the memory is free again. FREEDOM!
@stm52754 жыл бұрын
What is the point of "f"?
@hungngv9356 жыл бұрын
Thank you so much!
@realpython6 жыл бұрын
You're welcome!
@382946rthu7 жыл бұрын
I enjoy your videos and I will be looking for your book(s).
@mariuswirtz44277 жыл бұрын
Hi Dan, do you plan to release a printed version of your book in the future?
@mariuswirtz44277 жыл бұрын
Thanks!
@lawrencedoliveiro91046 жыл бұрын
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.
@manishjain62945 жыл бұрын
This video stucks after few seconds. Doesn't move after about 40sec. Kindly upload again.
@realpython5 жыл бұрын
The video appears to be working fine on our end, are you able to try another web browser? This may resolve the problem.
@manishjain62945 жыл бұрын
Hello Dan. Thanks for replying. It's is playing smoothly.
@licensetothrill6 жыл бұрын
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.dicicco14106 жыл бұрын
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.
@kebman4 жыл бұрын
The only generators I like, are those who generate money........
@Bengadeer4 жыл бұрын
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"
@kevinriordan1883 жыл бұрын
with Much(love): me.thank(you)
@poorgirl94585 жыл бұрын
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-ml6ej2 жыл бұрын
the video image is too poor, you need to fix it more