Python Tutorial: Context Managers - Efficiently Managing Resources

In this Python Programming Tutorial, we will be learning how to use context managers to properly manage resources. Context Managers are great for when we need to setup or teardown some resources during use. So these can be used for: open and closing files, opening and closing database connections, acquiring and releasing locks, and much much more. Let's get started...
The code from this video can be found at:
github.com/CoreyMSchafer/code...
Python Object-Oriented Series: goo.gl/ZSqx6y
✅ Support My Channel Through Patreon:
/ coreyms
✅ Become a Channel Member:
/ @coreyms
✅ One-Time Contribution Through PayPal:
goo.gl/649HFY
✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
✅ Corey's Public Amazon Wishlist
a.co/inIyro1
✅ Equipment I Use and Books I Recommend:
www.amazon.com/shop/coreyschafer
▶️ You Can Find Me On:
My Website - coreyms.com/
My Second Channel - / coreymschafer
Facebook - / coreymschafer
Twitter - / coreymschafer
Instagram - / coreymschafer
#Python

Пікірлер: 167

  • @VistasNatureWildlifeFilms
    @VistasNatureWildlifeFilms4 жыл бұрын

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

  • @kevinl7139
    @kevinl71396 жыл бұрын

    Still the best python teacher on the web

  • @coreyms

    @coreyms

    6 жыл бұрын

    Thanks! Glad you find these helpful!

  • @snookiewozo

    @snookiewozo

    4 жыл бұрын

    ​@@coreyms Someone stole your video: kzread.info/dash/bejne/fnqmqaeunsa7ps4.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
    @objnex4 жыл бұрын

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

  • @ErnestGWilsonII
    @ErnestGWilsonII5 жыл бұрын

    @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 KZread 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

    5 жыл бұрын

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

  • @ikhairi83

    @ikhairi83

    4 жыл бұрын

    i agree

  • @alexeyalex4271

    @alexeyalex4271

    4 жыл бұрын

    +

  • @misty_jeera

    @misty_jeera

    3 жыл бұрын

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

  • @mikeburt5877
    @mikeburt58776 жыл бұрын

    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.

  • @WakilSahak
    @WakilSahak3 жыл бұрын

    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!

  • @julioribeiro1909
    @julioribeiro19095 жыл бұрын

    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.

  • @Shaffooo125
    @Shaffooo1256 жыл бұрын

    Love the examples you gave. Very practical!

  • @ae7057
    @ae70575 жыл бұрын

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

  • @sarfarazsuri
    @sarfarazsuri Жыл бұрын

    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())

  • @bruh_yoh1702
    @bruh_yoh17022 жыл бұрын

    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.

  • @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 :-)

  • @sherafati
    @sherafati4 жыл бұрын

    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.

  • @FP_95
    @FP_95 Жыл бұрын

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

  • @iiit2tech
    @iiit2tech5 жыл бұрын

    As usual, excellent video Corey !

  • @pallenda
    @pallenda6 жыл бұрын

    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!

  • @ashutoshrath8810
    @ashutoshrath88106 жыл бұрын

    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!!

  • @sohailaqureshi
    @sohailaqureshi6 жыл бұрын

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

  • @m4ryou5h
    @m4ryou5h4 жыл бұрын

    Pure gold. Best tutorials i have ever seen

  • @ryantshims5252
    @ryantshims52524 жыл бұрын

    still improving my python skills thanks to you. definitly best

  • @piotrwln9348
    @piotrwln93485 жыл бұрын

    Congrats on having 200 000 subscribers now!

  • @javidaliyev310
    @javidaliyev3104 жыл бұрын

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

  • @LookNumber9
    @LookNumber96 жыл бұрын

    Very clear - as usual. Excellent.

  • @user-bp5xc9bv4m
    @user-bp5xc9bv4m3 жыл бұрын

    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 👍

  • @PavelZagalsky
    @PavelZagalsky6 жыл бұрын

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

  • @joemattress6177
    @joemattress61773 жыл бұрын

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

  • @ddpwe5269
    @ddpwe5269 Жыл бұрын

    Gratz on 1mil subs!

  • @thebuggser2752
    @thebuggser27522 жыл бұрын

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

  • @420nyk
    @420nyk3 жыл бұрын

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

  • @rushikesh8132
    @rushikesh81324 жыл бұрын

    Thankyou very much for explaining it so cleanly !

  • @eljefe919
    @eljefe9196 жыл бұрын

    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 😄

  • @roromaniac8
    @roromaniac82 жыл бұрын

    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 more, one will be created, but in case anyone was curious I double checked this was the case! Great videos as per the usual, Corey!

  • @Superogobongo
    @Superogobongo4 жыл бұрын

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

  • @donaldmartin2640
    @donaldmartin26405 жыл бұрын

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

  • @hubertcombomarketing2693
    @hubertcombomarketing26934 жыл бұрын

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

  • @coreyms

    @coreyms

    4 жыл бұрын

    Thanks!

  • @gravitycuda
    @gravitycuda3 жыл бұрын

    Beautiful explanation with great examples :) Thank you !!

  • @lukakovacevic3183
    @lukakovacevic31836 жыл бұрын

    Thank you for this! Best tutorials!

  • @drygordspellweaver8761
    @drygordspellweaver87612 жыл бұрын

    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!

  • @UsmanSaadat
    @UsmanSaadat2 жыл бұрын

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

  • @clamagdeleine
    @clamagdeleine6 жыл бұрын

    Hi Corey, Very good video to unterstand Python contextmanager.

  • @VaibhavSharma-zj4gk
    @VaibhavSharma-zj4gk Жыл бұрын

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

  • @hongtaekim1504
    @hongtaekim15044 жыл бұрын

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

  • @wisdomeispower
    @wisdomeispower Жыл бұрын

    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

  • @ednilsonalveslomazi2660
    @ednilsonalveslomazi26604 жыл бұрын

    Really nice video. Explains a lot. Thanks.

  • @prabhathkota107
    @prabhathkota1075 жыл бұрын

    Explained beautifully

  • @treelight1707
    @treelight17076 жыл бұрын

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

  • @meganoob9281
    @meganoob92816 жыл бұрын

    Great video man. Thank you.

  • @rangabharathjinka3556
    @rangabharathjinka35566 жыл бұрын

    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:-)

  • @diegosorte
    @diegosorte5 жыл бұрын

    You are simply the best!

  • @francismcguire6884
    @francismcguire68844 жыл бұрын

    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!

  • @annaburshtyko5714
    @annaburshtyko57143 жыл бұрын

    Thank you for the great explanation!

  • @zekunzhang745
    @zekunzhang7456 жыл бұрын

    this is crazy man so good

  • @blaFERNANDOblablabla
    @blaFERNANDOblablabla5 ай бұрын

    This video was amazing, thank you so much

  • @abhisheksharma-xq5pe
    @abhisheksharma-xq5pe6 жыл бұрын

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

  • @moishfrankel1973
    @moishfrankel19733 жыл бұрын

    clear and simple explanation of of contextmanager, thanks

  • @xiaoweidu4667
    @xiaoweidu4667 Жыл бұрын

    great explanation! thank you

  • @abhijeetduttPandey
    @abhijeetduttPandey3 жыл бұрын

    You're best Corey!

  • @ilanaizelman3993
    @ilanaizelman39935 жыл бұрын

    Gold!!!!!! Thank you.

  • @JorgeEscobarMX
    @JorgeEscobarMX11 ай бұрын

    New super power unlocked!! thanks!

  • @suvodeeproy6769
    @suvodeeproy67696 жыл бұрын

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

  • @StevenTse
    @StevenTse5 жыл бұрын

    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!!

  • @ChrisHalden007
    @ChrisHalden0074 жыл бұрын

    Excellent. Thx!!!!

  • @davidm.johnston8994
    @davidm.johnston89946 жыл бұрын

    Great video, thanks.

  • @dawnS33ker
    @dawnS33ker10 ай бұрын

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

  • @Ilyssuii
    @Ilyssuii3 жыл бұрын

    This was oo amanzing, and fun to do

  • @parikshitrao2948
    @parikshitrao29482 жыл бұрын

    Even after 3 years pog tutorials

  • @Hubbins99
    @Hubbins995 жыл бұрын

    Well done.

  • @MuhammedBasil
    @MuhammedBasil3 жыл бұрын

    Thanks for sharing.

  • @gibuzzx6018
    @gibuzzx60182 жыл бұрын

    Super good explanation thx

  • @mohammadalaaelghamry8010
    @mohammadalaaelghamry80108 ай бұрын

    Great video thank you.

  • @bakrfrag4084
    @bakrfrag40846 жыл бұрын

    great video and great info

  • @haxsyshackerman4174
    @haxsyshackerman4174 Жыл бұрын

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

  • @lefu7812
    @lefu7812 Жыл бұрын

    Thank you!

  • @edwingarcia5043
    @edwingarcia50432 жыл бұрын

    Thanks again.

  • @younghwanchae1422
    @younghwanchae14224 жыл бұрын

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

  • @Pyrografpl
    @Pyrografpl2 жыл бұрын

    Interesting, thank you

  • @mohamedsleymi4318
    @mohamedsleymi43186 жыл бұрын

    thank you very much , you are awesome

  • @thepresistence5935
    @thepresistence5935 Жыл бұрын

    # 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())

  • @mohamadibrahim7283
    @mohamadibrahim72836 жыл бұрын

    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

  • @JacobScott0000
    @JacobScott00004 жыл бұрын

    you're the man

  • @vinaykn1
    @vinaykn16 жыл бұрын

    You are Awesome

  • @hiteshchalise3988
    @hiteshchalise39886 жыл бұрын

    really good video

  • @c1337
    @c13376 жыл бұрын

    You Are The Best

  • @DdongK
    @DdongK5 жыл бұрын

    Phenomenal

  • @witherfly5811
    @witherfly5811 Жыл бұрын

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

  • @raghavgupta1157
    @raghavgupta11576 жыл бұрын

    just wow!

  • @arinzealex
    @arinzealex4 жыл бұрын

    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?

  • @sunnyxd5000
    @sunnyxd5000 Жыл бұрын

    cool stuff :)

  • @user-cy3je1xd1c
    @user-cy3je1xd1c4 жыл бұрын

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

  • @norindethmao
    @norindethmao6 жыл бұрын

    I am pretty thanks for this video and your videos. No doubt, just I need to try myself. And I would like to show the sending without and with attachment files in Python. Hope you are doing fine.

  • @edmonda.9748
    @edmonda.97482 жыл бұрын

    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

  • @satyasarathi1985
    @satyasarathi19856 жыл бұрын

    nice video...

  • @lukerengel8533
    @lukerengel85336 жыл бұрын

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

  • @arsenalkarim2253

    @arsenalkarim2253

    6 жыл бұрын

    me2

  • @RC-bl2pm

    @RC-bl2pm

    6 жыл бұрын

    yeah we sure could use a flask/peewee tut!!!

  • @namesjoe911
    @namesjoe9113 жыл бұрын

    awesome

  • @adamoja4295
    @adamoja42953 жыл бұрын

    Nice

  • @MohammedAbuObaid
    @MohammedAbuObaid4 жыл бұрын

    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

  • @ketanbutte3497
    @ketanbutte34973 жыл бұрын

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

  • @johnbennett1465
    @johnbennett14654 жыл бұрын

    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.

  • @BiGreDNoSecoMpAny
    @BiGreDNoSecoMpAny4 жыл бұрын

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

  • @santoshkumarswarnkar7158
    @santoshkumarswarnkar715811 ай бұрын

    nice