Python Tutorial: Context Managers - Efficiently Managing Resources

Поделиться
HTML-код
  • Опубликовано: 29 ноя 2024

Комментарии • 168

  • @VistasNatureWildlifeFilms
    @VistasNatureWildlifeFilms 4 года назад +131

    10+ years using Python professionally and I still learning things from Corey.

  • @kevinl7139
    @kevinl7139 6 лет назад +249

    Still the best python teacher on the web

    • @coreyms
      @coreyms  6 лет назад +4

      Thanks! Glad you find these helpful!

    • @snookiewozo
      @snookiewozo 4 года назад +7

      ​@@coreyms Someone stole your video:
      ruclips.net/video/LFrGEuncUvk/видео.html

    • @RestlessSixtie
      @RestlessSixtie 3 года назад

      @@snookiewozo Hope @Corey Schafer sees this. That other dude is trying to take credit of something for which he has not done any hard work.

    • @thedarkknight579
      @thedarkknight579 2 года назад

      Not still, it's Forever 🙏

  • @objnex
    @objnex 4 года назад +37

    Two languages helped to be learnt very well througout tutorials. 1. English 2. Python.
    Thanks a lot.

  • @ErnestGWilsonII
    @ErnestGWilsonII 6 лет назад +105

    @CoreySchafer after several months of watching videos on the internet and going through various online training including ones I purchased, I can safely say this channel and specifically Corey Schafer has the best Python training videos on RUclips and perhaps on the entire internet! Thank you very much for taking the time to make these videos and share them with all of us! I find myself repeatedly revisiting your videos as an excellent training reference, well done! I am of course subscribed with notifications turned on and thumbs up! I wish I could give this channel a million thumbs up! I let all the videos play to the end on both my browser and on Chromecast and I hope that boosts your statistics and views, you certainly deserve credit for excellent training and making the Internet a better place for us all! I will be joining your Patreon and helping to support this channel, something I do not often do with limited funding and only reserve the very best content which this certainly is!

    • @coreyms
      @coreyms  6 лет назад +12

      Thanks, Ernest! That means a lot to me. I'm glad to hear you've found the videos helpful!

    • @ikhairi83
      @ikhairi83 5 лет назад +1

      i agree

    • @alexeyalex4271
      @alexeyalex4271 4 года назад +1

      +

    • @misty_jeera
      @misty_jeera 3 года назад +1

      This is such a wholesome comment lol, made me feel good : )

  • @bruh_yoh1702
    @bruh_yoh1702 2 года назад +1

    Lol, I just started learning python a year ago and now i come across sth in my Documentation that requires some knowledge on Context managers, fuuny part is the next videon is "EXPERT TUTORIAL CONTEXT MANAGERS by Tech With Tim" The expert intro just eased my frustrations for having difficulties to understand this concept fully.

  • @WakilSahak
    @WakilSahak 3 года назад +1

    Never thought there is someone who give us such a proper & useful explanation on these lessons!
    Watching after 3 years of its release still find it way useful!
    Simply the best on this platform, your big fan from Afghanistan Corey Sir!

  • @witherfly5811
    @witherfly5811 2 года назад +1

    As soon as I saw Lorem Ipsum as placeholder I knew this guy was legit

  • @cuthbertmilligen
    @cuthbertmilligen Год назад

    As a long-time Java professional, I'm constantly reminded how concise Python is and your excellent tutorials really show it off to its best advantage. please, keep them coming :-)

  • @drygordspellweaver8761
    @drygordspellweaver8761 2 года назад

    Don’t know why but halfway through this vid I had an idea for a simple typing practice program. Then I could practice code and get better at typing it too... lmao your genius is rubbing off on me!

  • @roromaniac8
    @roromaniac8 3 года назад +2

    A minor note, but the code at 12:51 doesn't actually work if the mode is 'r' and the file doesn't exist in the directory. This is because f never gets assigned a value since open will yield a FileNotFoundError. Therefore, this code will still result in an error because f isn't an object that can be closed. A very minor point, especially since if a file doesn't exist in write mode, one will be created, but in case anyone was curious I double checked this was the case! Great videos as per the usual, Corey!

    • @ianfarai4982
      @ianfarai4982 2 месяца назад

      maybe something like below :
      from contextlib import contextmanager
      @contextmanager
      def open_file(filename,mode):
      file = None
      try:
      file = open(filename,mode)
      yield file
      finally:
      if file is not None:
      file.close()

  • @wisdomeispower
    @wisdomeispower 2 года назад

    I know this is pretty old video but anyway wanna say thank you for showing what's going on under the hood, it helps with understanding code so much

  • @sarfarazsuri
    @sarfarazsuri 2 года назад +2

    15:40
    if someone is interested doing the exercise using class, refer below :)
    class Directorylister:
    def __init__(self, destination):
    self.cwd = os.getcwd()
    self.destination = destination
    def __enter__(self):
    os.chdir(self.destination)
    def __exit__(self, exc_type, exc_val, traceback):
    os.chdir(self.cwd)
    with Directorylister(""):
    print(os.listdir())

  • @dawnS33ker
    @dawnS33ker Год назад

    Corey is the 👑 of Python, the best in the business.

  • @hubertcombomarketing2693
    @hubertcombomarketing2693 4 года назад +4

    I just can't help repeating myself. Great Python tutorial. Thank You.

  • @user-bp5xc9bv4m
    @user-bp5xc9bv4m 3 года назад

    I remember subscribing to your channel but don't how it got unsubscribed. Subscribed again. Wonderful info after 3 years of my python career. Thanks 👍

  • @hongtaekim1504
    @hongtaekim1504 4 года назад +4

    When it comes to Python teaching, you're by far the best in the entire earth. Thank you so much!

  • @m4ryou5h
    @m4ryou5h 4 года назад +1

    Pure gold. Best tutorials i have ever seen

  • @thepresistence5935
    @thepresistence5935 2 года назад

    # I made this with class!
    # with context manager
    class ChangeDir:
    def __init__(self, destination):
    self.destination = destination
    def __enter__(self):
    self.cwd = os.getcwd()
    os.chdir(self.destination)
    def __exit__(self, exc_type, exc_val, traceback):
    os.chdir(self.cwd)
    with ChangeDir('sample'):
    print(os.listdir())
    with ChangeDir('sample2'):
    print(os.listdir())

  • @ryantshims5252
    @ryantshims5252 4 года назад +2

    still improving my python skills thanks to you. definitly best

  • @sherafati
    @sherafati 4 года назад +2

    I see it my responsibility to drop a like and say thank you for how well you explain subjects in your videos, as if you really knew what the audience does not understand and you explain that very well. This is just so much better than the courses i paid for.

  • @javidaliyev310
    @javidaliyev310 4 года назад +2

    Thank you!! It is the best tutorial of context managers

  • @donaldmartin2640
    @donaldmartin2640 5 лет назад +2

    I have a white belt in Python and this really helps. Thanks

  • @VaibhavSharma-zj4gk
    @VaibhavSharma-zj4gk Год назад +1

    Hi Corey Please keep making Python tutorials. As many beginners, intermediate concept are already covered please make on advanced topics. They are very helpful...

  • @parikshitrao2948
    @parikshitrao2948 3 года назад

    Even after 3 years pog tutorials

  • @mikeburt5877
    @mikeburt5877 6 лет назад +2

    Corey, thank you for posting these tuts on Python. I've found them all so interesting. I really enjoyed understanding how context managers work and thanks to your video on them I've already made use of one in a project. Thanks again, buddy. They're much appreciated.

  • @Shaffooo125
    @Shaffooo125 6 лет назад +6

    Love the examples you gave. Very practical!

  • @rushikesh8132
    @rushikesh8132 4 года назад +1

    Thankyou very much for explaining it so cleanly !

  • @ashutoshrath8810
    @ashutoshrath8810 7 лет назад +3

    Thank you for making our lives easier Corey. Could you please create a series related to advance oops concepts and how and where we can implement them. Thanks!!

  • @FP_95
    @FP_95 2 года назад

    Love your tutorials man. Been a huge help!
    Simple, to the point & free.
    PPL like you make the earth a better place!

  • @ae7057
    @ae7057 5 лет назад +3

    Corey, i enjoyed every second of this video, simple and straightforward.
    Hope to see a video about coroutines as well.
    Thanks.

  • @JorgeEscobarMX
    @JorgeEscobarMX Год назад

    New super power unlocked!! thanks!

  • @ketanbutte3497
    @ketanbutte3497 3 года назад

    python is just like corey- clear, consise and simple to understand.

  • @julioribeiro1909
    @julioribeiro1909 5 лет назад +2

    Corey, this video is amazing. You're a very good instructor and your contents are really useful and very easy to understand. Thank you for all videos you've been posting.

  • @ddpwe5269
    @ddpwe5269 2 года назад

    Gratz on 1mil subs!

  • @Александр-р3э3м
    @Александр-р3э3м 4 года назад

    with CoreysBestTutorial('Great Explanation', 'Awesome examples'):
    set('Like')
    execute('Subscribe')
    say('Haven't seen better tutorials, than yours!')

  • @420nyk
    @420nyk 4 года назад

    That example really helped me understand it really well. Thanks!

  • @joemattress6177
    @joemattress6177 4 года назад

    Excellent instruction as with all of your Python tutorials. Thank you!

  • @iiit2tech
    @iiit2tech 5 лет назад +1

    As usual, excellent video Corey !

  • @Superogobongo
    @Superogobongo 4 года назад +1

    Crystal clear, as always. Thank you very much..

  • @sohailaqureshi
    @sohailaqureshi 7 лет назад

    Excellent tutorial, simple words covers this difficult topic with ease.

  • @moishfrankel1973
    @moishfrankel1973 3 года назад

    clear and simple explanation of of contextmanager, thanks

  • @UsmanSaadat
    @UsmanSaadat 2 года назад

    Thank you so much for this amazing video like many others. This content will keep helping many new developers for always. God bless you.

  • @LookNumber9
    @LookNumber9 7 лет назад +1

    Very clear - as usual. Excellent.

  • @prabhathkota107
    @prabhathkota107 5 лет назад +1

    Explained beautifully

  • @thebuggser2752
    @thebuggser2752 3 года назад

    Again a great well thought out and clear presentation. Thanks!!

  • @piotrwln9348
    @piotrwln9348 6 лет назад +1

    Congrats on having 200 000 subscribers now!

  • @francismcguire6884
    @francismcguire6884 5 лет назад +1

    This was great ... I think I can use a generator in a project I am currently working on. I’m trying to mimic a library I am familiar with in another language that links events with commands through an XML file. I’ll put the project on GitHub for you and your community to review and get some feedback in the next few days. Thanks!

  • @younghwanchae1422
    @younghwanchae1422 4 года назад

    My brain just bursts after watching this video, but super great and useful contents, I just need some pratice...

  • @eljefe919
    @eljefe919 6 лет назад +1

    Hey Corey. Excellent video. Your channel is the best on YT in my humble opinion. Can you create a series of videos concerning data structures and algorithms for technical interviews? I think you’d be awesome at it since your teaching ability is 10 out of 10 😄

  • @pallenda
    @pallenda 7 лет назад

    Great video! Well planned video with first showing the how to recreate something people have used, you then build on that with a simple but great example with the change_dir context manager. Well done!

  • @lukerengel8533
    @lukerengel8533 7 лет назад +12

    Hey Corey Nice video! can't wait for you tutorials on Django and Flask

  • @ednilsonalveslomazi2660
    @ednilsonalveslomazi2660 5 лет назад +1

    Really nice video. Explains a lot. Thanks.

  • @clamagdeleine
    @clamagdeleine 6 лет назад +1

    Hi Corey, Very good video to unterstand Python contextmanager.

  • @rangabharathjinka3556
    @rangabharathjinka3556 7 лет назад +15

    Hi Corey Shafer, Nice video with a nice explanation.Thank you from the bottom of my heart for ur videos.Hope to see more videos on web and app development using python.Thank you.Bye:-)

  • @gravitycuda
    @gravitycuda 4 года назад

    Beautiful explanation with great examples :) Thank you !!

  • @diegosorte
    @diegosorte 5 лет назад +1

    You are simply the best!

  • @PavelZagalsky
    @PavelZagalsky 7 лет назад

    Excellent video! I really need to use context managers more!

  • @abhijeetduttPandey
    @abhijeetduttPandey 3 года назад

    You're best Corey!

  • @blaFERNANDOblablabla
    @blaFERNANDOblablabla 10 месяцев назад

    This video was amazing, thank you so much

  • @StevenTse
    @StevenTse 5 лет назад +1

    thankyou, and indeed Corey is the best Python teacher on the internet. if I may, can you teach us on flutter with Python, ethical hacking, python on raspi...? thankyou!!

  • @annaburshtyko5714
    @annaburshtyko5714 4 года назад

    Thank you for the great explanation!

  • @suvodeeproy6769
    @suvodeeproy6769 6 лет назад

    So nice explanation i had never seen before. Please make a series of C programming for us.

  • @abhisheksharma-xq5pe
    @abhisheksharma-xq5pe 7 лет назад +2

    As usual remarkable video...chorey request you to create bit advance object oriented concept videos

  • @lukakovacevic3183
    @lukakovacevic3183 7 лет назад +1

    Thank you for this! Best tutorials!

  • @xiaoweidu4667
    @xiaoweidu4667 Год назад

    great explanation! thank you

  • @haxsyshackerman4174
    @haxsyshackerman4174 2 года назад

    first time i saw your channel i subscribed to it 😁😏

  • @BiGreDNoSecoMpAny
    @BiGreDNoSecoMpAny 4 года назад

    Favorite moment 18:50 - "You can do whatever you wanna .. dir"

  • @treelight1707
    @treelight1707 7 лет назад

    As always, I learned something new from your video, thanks

  • @arinzealex
    @arinzealex 4 года назад +2

    Thanks so much for the video. Loved it. However, I am not clear on the last code presented. why did you needed the @contextmanger at top of the function. Would the function still have worked without the context manager?

  • @Ilyssuii
    @Ilyssuii 3 года назад

    This was oo amanzing, and fun to do

  • @gibuzzx6018
    @gibuzzx6018 2 года назад

    Super good explanation thx

  • @zekunzhang745
    @zekunzhang745 6 лет назад +1

    this is crazy man so good

  • @ChrisHalden007
    @ChrisHalden007 5 лет назад +1

    Excellent. Thx!!!!

  • @ilanaizelman3993
    @ilanaizelman3993 5 лет назад +1

    Gold!!!!!! Thank you.

  • @meganoob9281
    @meganoob9281 7 лет назад

    Great video man. Thank you.

  • @mohammadalaaelghamry8010
    @mohammadalaaelghamry8010 Год назад

    Great video thank you.

  • @MuhammedBasil
    @MuhammedBasil 3 года назад

    Thanks for sharing.

  • @johnbennett1465
    @johnbennett1465 5 лет назад

    While I can see cases where the try-except code would be important, in this case it is useless or broken. If the first change directory fails, you will still be in the correct dorectory, so no need to change back. If the get directory fails, then the change directory in the finally clause will fail causing an extra error masking the actual problem.

  • @sachinparashar8822
    @sachinparashar8822 4 года назад +1

    Hi I have confusion that if we are using context manager then why we are using try and finally. I think it's automatically handles everything

  • @Hubbins99
    @Hubbins99 6 лет назад +1

    Well done.

  • @Pyrografpl
    @Pyrografpl 2 года назад

    Interesting, thank you

  • @edwingarcia5043
    @edwingarcia5043 3 года назад

    Thanks again.

  • @mohamadibrahim7283
    @mohamadibrahim7283 7 лет назад +2

    hi corey, i love your videos so much, can i just make one request and i hope you take it into consideration
    it will help me and alot of people too
    can you make 3 playlists about python data scientists libraries(pandas,matplotlib,numpy)
    it will be very helpful
    thank you in advance and keep up the good work

  • @allmazd
    @allmazd Год назад

    Can you explain why do we need round brackets after the class name in here? In your previous videos they were used only for child classes? Thanks in advance for explaining

  • @edmonda.9748
    @edmonda.9748 2 года назад

    Thanks for your videos, everything is perfect about them
    I am working on a program in which a method (no_sync(), a context manager in DistributeDataParallell) is being used like a method to an instance of another class
    Not sure if I am making any sense

  • @DrSnej
    @DrSnej 3 года назад

    TECHNICAL Question.
    I would assume that (8:00) 'f' inside the context manager would be just in scope of that context manager. Surprised that printing 'f.closed' even works and not throwing NameError.
    #edit: omg i have been thinking this the whole time, that conetxt manager has its own scope...

  • @lefu7812
    @lefu7812 Год назад

    Thank you!

  • @JacobScott0000
    @JacobScott0000 5 лет назад +1

    you're the man

  • @RanGavriely
    @RanGavriely 6 месяцев назад

    You should call f.flush() after the write opperation. I am supprised the print at the end even returned True as Python isnt writing to disk as soon as you call the write command. this code can lead to incomplete write to disk

  • @davidm.johnston8994
    @davidm.johnston8994 7 лет назад

    Great video, thanks.

  • @priteshugrankar6815
    @priteshugrankar6815 2 года назад

    How does the mode attribute gets set to the actual mode attribute of file? Where does that mapping happen?

  • @MohammedAbuObaid
    @MohammedAbuObaid 4 года назад

    Hey Corey,
    Thanks a lot for the amazing channel and super tut’s. Simply, the best out there!
    My question here: why you are not catching a possible exception with the “except” clause before you head to the “finally” clause?
    It seems I’m missing how an exception is been handled should one be raised here
    Can you please clarify that point?
    Thanks again..
    Mohammed

  • @bakrfrag4084
    @bakrfrag4084 7 лет назад

    great video and great info

  • @unique1o1-g5h
    @unique1o1-g5h 7 лет назад +9

    please do a video on pickle

  • @vinaykn1
    @vinaykn1 6 лет назад +1

    You are Awesome

  • @yltfy
    @yltfy 4 года назад

    Hi, reat video! Just one question, do we still need to wrap the codes by a try-except block? Isn't context manager supposed to handle errors automatically?

  • @DdongK
    @DdongK 5 лет назад +1

    Phenomenal

  • @bokkenka
    @bokkenka 7 лет назад +1

    Great video! Thanks! One question... In the change_dir() example, if there is an error, will it have the original directory in cwd so it can chdir back to it in the finally section?

    • @coreyms
      @coreyms  7 лет назад

      Yes, it should.

  • @konstantinkouptsov7513
    @konstantinkouptsov7513 5 лет назад +1

    6:07 What is the scope of variable `f`? I would expect it to be local in `with` construct, but `f.close()` is placed outside.

    • @NicolasChanCSY
      @NicolasChanCSY 4 года назад

      With-statement does not create a new scope and thus f is still defined outside of the with-statement.
      You see, the with-statement is equivalent to try-except-finally and try-except-finally doesn't create a new scope.
      In this case, we try to assign f = open(filename, ...) and finally close it when calling the __exit__(). `f` is still referencing a file object after the with-statement just as it does when getting through a try-except-finally block.
      Reference:
      1) stackoverflow.com/questions/6432355/variable-defined-with-with-statement-available-outside-of-with-block
      2) PEP 343

  • @Sss222ddd
    @Sss222ddd 6 лет назад

    thank you very much , you are awesome