Building A Custom Context Manager In Python: A Closer Look

Building A Custom Context Manager In Python: A Closer Look

ArjanCodes

2 года назад

46,123 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Brian Pack
Brian Pack - 24.03.2023 04:32

Using non invisible characters to define code blocks? We've gone full circle, everyone.

Ответить
ArtForEigen
ArtForEigen - 06.02.2023 22:09

Tapped in for a seagull manager video but totally disappointed to see no seagulls. Disliked :p

Ответить
ΙΟΡΔΑΝΗΣ ΠΕΛΕΖΙΚΗΣ
ΙΟΡΔΑΝΗΣ ΠΕΛΕΖΙΚΗΣ - 31.01.2023 10:32

This is a video I was looking for! A question. Why commit is included in a finally block and not in an else block. Is there a certain logic on why one is prefered than the other? Thanks in advance

Ответить
Miguel Vásquez
Miguel Vásquez - 06.10.2022 17:55

I already knew this, but what a good video

Ответить
al i
al i - 23.09.2022 19:01

Super helpfull video! I have hower some problems putting this to an actual usage. Lets say i want to have a databasemanager class that that handles all conection. Can create a new db on a server create new tables on existing dbs.....delete those . Further more it should be able to execute parameterized querrys were the querry is a variable and so on .... How would something like this been done professionally? Especially if we are dealing with a remote lets say sql server instance?

Ответить
İbrahim Tıpırdık
İbrahim Tıpırdık - 20.09.2022 21:37

I downloaded the document and didn't even realize I finished it in one go. Thank you for your thoughts and valuable information

Ответить
Simon Howroyd
Simon Howroyd - 08.09.2022 22:36

Is there a way of using a context managed object at class scope rather than function scope. For example, acquiring the resource in _init_ then releasing it when the object gets destroyed. Hypothetical example; a logger class that opens a file when it is created, closes when destroyed.

For context, I have a very performant function which extracts data from an FPGA, does some maths then needs to be logged. I don't like the idea of having to do a "with open(fn) as f" in every single loop for performance. (This is running at 2kHz and the "while" isn't even in this function contained by this class)

Ответить
Nathan Toulbert
Nathan Toulbert - 24.04.2022 05:25

I really hope I'm a seagull in my next life. Just imagine living life as the shitter, and not the shittee!!!

Ответить
Raja Duraisingam
Raja Duraisingam - 10.03.2022 20:21

Hi Arjan, How do we implement connection pooling in this case? Do we need to move the connection creation line outside of the function?

Ответить
Jim Winters
Jim Winters - 01.03.2022 21:26

Thanks for a fine explanation of context managers. A small quibble: I don't think "with" makes a new scope, because I have code that assigns a buffer to a new variable within a "with" and then accesses the variable outside of the "with" just fine.

Ответить
tuverentetil
tuverentetil - 21.02.2022 13:57

Hi Arjan, can you also add snippets how to test code you're writing ? Seems that test are largely overlooked i.e i'd like to learn how to use pytest with context manager.

Ответить
Tobias Triesch
Tobias Triesch - 17.02.2022 00:17

Cool video! I learn something new every time :)
I also have a suggested topic/question:
What's your take on normal SQL queries vs object-relational mappings, e.g. using SQLalchemy? Do or do not? How can I make best use of context managers here?

Ответить
Bigdaddy
Bigdaddy - 13.02.2022 05:03

Really glad I came across this channel. Been dabbling in python for about 4 months and have made some really good progress. Feel confident I can create everything I want, but I'm a chemical engineer, not a coder....but I want to create good habits and make stuff that a coder will not roll their eyes reading. This is the first channel that just skips the same repetitive basic coding stuff 99% of channels focus on and just focuses on being a smart coder. And it's all delivered so well. I find I learn more in a 10 minute video from you than some of these bigger channels don't even do in a 2 hour video. Plus your fast typing is so soothing lol.

Ответить
Nikoloz Adeishvili
Nikoloz Adeishvili - 13.02.2022 01:35

What will be the return type for open_db method in this case?

Ответить
Ric Hard
Ric Hard - 08.02.2022 20:06

A bit out of context (no pun intended ;-): why I need to declare a function explicitely as "async" (as in async def main()" when using an async-y keyword or calling some async function makes it cristal clear, that the function itself is per definition async? Saw this in multiple languages already and always asked myself "wth" is this boilerplate for?

Ответить
Sam Hutchinson
Sam Hutchinson - 07.02.2022 14:45

I like your style

Ответить
Shlomo Gottlieb
Shlomo Gottlieb - 07.02.2022 14:43

Video idea:
Python coroutines and how it's used with 'yield' and 'yield from'. No matter how many times I look it up, I never manage to wrap my head around it.

Ответить
zen
zen - 07.02.2022 08:38

do any of the ways shown have performance repercussions? would one way be more performant than another?

Ответить
Golam Muhaimeen
Golam Muhaimeen - 07.02.2022 05:49

Soo good man! Great stuff! Love it!

Ответить
Stefan S
Stefan S - 06.02.2022 15:07

Hi there,

could you please me do download and install these 2 packages logging and sqlite3 ? Beause i tried from pycharm and comand prompt but without success :
pip install logging
ERROR: Could not find a version that satisfies the requirement logging (from versions: 0.4.9.6)
ERROR: No matching distribution found for logging

pip install sqlite3
ERROR: Could not find a version that satisfies the requirement sqlite3 (from versions: none)
ERROR: No matching distribution found for sqlite3

Thanks,

Ответить
Andrzej Grzegorczyk
Andrzej Grzegorczyk - 06.02.2022 14:49

I have impression you are looking into my daily activity and send me suggestions how to improve my code :) Thank you

Ответить
Hamza
Hamza - 06.02.2022 04:32

Cool video and nice beard Arjan

Ответить
channalbert
channalbert - 06.02.2022 00:54

I might be missing the point here, but what is the difference between putting “connection.close()” after a try-catch clause and adding it inside “finally”?

Ответить
Kemal Cihan Baştak
Kemal Cihan Baştak - 05.02.2022 15:10

Since you used yield function in connection part, can you make a video about when to use yield instead of return

Ответить
Artem Isakhanian
Artem Isakhanian - 05.02.2022 14:41

Thanks for videos Arjan, they're helpful. First time I got acquainted with context managers is when I read Python Tricks book by Dan Bader

Ответить
Jordan Silke
Jordan Silke - 05.02.2022 05:08

Helpful video with clear, practical examples as always!

Ответить
virtualraider
virtualraider - 05.02.2022 03:30

Love the video! Just a small nitpick: I wouldn't put the commit inside finally, because you don't want to save things in a dirty state.

I would put it on the else condition, or better yet, in a transaction context manager 🤓

Ответить
djl
djl - 05.02.2022 01:18

Nicely done! concise and thorough. I looked into custom context managers a few months ago and like many, settled on the class version, but after this video I think I'll be leaning towards the decorator.

Ответить
Diego
Diego - 04.02.2022 23:57

Great video as always.
It would be nice if you make a video explaining generators and coroutines in detailed, just as an idea 😊

Ответить
John Mansell
John Mansell - 04.02.2022 23:20

Great video. Loved the much steadier camera angles. And I learned about the context manager decorator. I didn't know we could write our own context managers without explicitly writing the dunder functions. Thanks!

Ответить
AlpNix Tech
AlpNix Tech - 04.02.2022 22:56

Cool! It's nice to know there are much more uses cases of context managers than opening and closing files 😅

Ответить
Dmitry Korzunin
Dmitry Korzunin - 04.02.2022 22:44

What is the code hinting when you start the coding, is it some vscode extension?

Ответить
1337Hammersmith
1337Hammersmith - 04.02.2022 22:41

It's amusing that this was the exact thing i stopped on this week, and thought, there has to be an easier way to manage contexts :)
Insightful and well paced as always

Ответить
ekebro
ekebro - 04.02.2022 22:28

I just have to protest. SQLute is an objectively better name for the class. When in doubt, go for the musical alternative.

Ответить
Rahul Prasad
Rahul Prasad - 04.02.2022 22:09

Tbh, i like the class version better.

Ответить
Vincenzo Cortino
Vincenzo Cortino - 04.02.2022 21:45

afaik with statement doesn't create a scope

Ответить
Sers
Sers - 04.02.2022 21:43

Information for people not from USA!
I used more than one-year Webull. One month ago, we were faced with the fact of restricted accounts for the whole of my country.
You wake up and get happy news. Just like that.
After several nervous days of waiting, they force us to sell all and withdraw money in 10 days. Transfer stocks to another broker are not allowed they say (was also wrong information).
The unprofessional and irresponsible attitude from Webull led to huge losses.
Forewarned is forearmed.
Now using Interactive Brokers.

Ответить
Vasilije Stosic
Vasilije Stosic - 04.02.2022 21:00

Today I actually worked with custom context manager, dealing with FTP connections. This video is really good for deeper understanding of context mangers. Well done! 👏👏

Ответить
Austin Witherspoon
Austin Witherspoon - 04.02.2022 20:36

I knew about the class version of a context manager- but never knew about the function decorator version! Super cool.

Ответить
ishtiaque hussain
ishtiaque hussain - 04.02.2022 20:35

Learned something new, as always! Thank you! (btw, also learned how to pronounce your name, I was wrong the whole time) :D

Ответить
J. Reddick
J. Reddick - 04.02.2022 20:11

Man! Every clip always has some depths! Love all the series! BTW, is there any chance that we can see UNCLE BOB explains how the INFAMOUS thread works in Python? lol

Ответить
manonthedollar
manonthedollar - 04.02.2022 20:03

In production code, would you put the entire `with` block inside a `try` block for cases where a connection can't be made (maybe application.db can't be opened and so the `finally` block would throw an exception too)? That's where I start to lose confidence in my design, because especially when I'm doing more than just a couple of things with an open db connection or file handle, most of my code is indented several levels inside some sort of massive function->try->with structure and it "feels" wrong but I don't know what I could be doing better.

Ответить
Fryderyk Chopin
Fryderyk Chopin - 04.02.2022 19:44

Nice video

Ответить
Roy Wood
Roy Wood - 04.02.2022 19:33

Very timely video, considering what I'm working on today. I actually prefer the class-based context manager to the decorator version, though that is probably because I haven't used generators that much. Anyway, nice work on the video.

Ответить
Nate River
Nate River - 04.02.2022 19:28

Make please a video about descriptors and their role in a python ecosystem

Ответить
Andrew Baxter
Andrew Baxter - 04.02.2022 19:17

It’s like your reading my mind. I wish I had a channel this good to help me improve with my understanding of Git CI/CD workflows and pipelines.

Ответить
Rakesh A
Rakesh A - 04.02.2022 19:16

Your content is excellent and the quality of the videos are Top Notch. You deserve alot of views and subs ❣️🔥

Ответить