This chanel has a very high python value. It's nothing like the others, recycling docummentation or from one another. You can easilly see this on the file examples, where there are codecs and itertools correctly used.
Yes I like this channel for quick examples of certain features and learning why things are the way they are and what you can do with those features. For software architecture and design patterns I like Arjan Codes. Especially the innovative code roasts series
Yeah, everybody else for this language has one of a few gimmicks running. Selling entry level courses, covering some thing with a crummy library under the clickbait premise that its a smart to thing to learn because it uses “so few lines of code”, or, well, intermediate level courses. Almost no explaining builtins and patterns.
Quite useful when I want to know something. Straight, to the point. I still think it’s funny that I went: time to learn python to make a quadratic cracker despite having no experience in non block coding, and after a summer, I am now ok at python!
I really like how you get straight to the point and give clear and concise explanations. This channel is one of the best if not the the best resource for understanding more difficult concepts in python.
Excellent, just as always! The Python level you teach is just another level. Love your videos. Can you do a tutorial on super function as well? I would really appreciate that.
Yes, that would be good, especially in the case of multiple inheritance. Actually, the do's-and-don't's of multiple inheritance in general would be great
Man your videos are awesome. I like that they are so much on point without artifical fluff to make them unnecessarily longer. Every video has one topic and sticks to it similar to "a function should do one job only" :). Great job!
I love those videos where you look at one single issue and explain it in-depth! while all of those videos may already exist on yt, most are just not as well made. yours are a joy to watch!
The value of a singleton is when you need an abstraction to something where there is an actual constraint that "there can be only one". The classic example is hardware access. Suppose you open a connection to a device that only supports a single connection (e.g. a COM port), and a set of objects that can access that device. Making the device abstraction a singleton is a great design pattern. Any object can instantiate the device object. If it's the first one, a new object is instantiated. If it's a subsequent construction, the object gets a reference to the already instantiated device.
Holy shit, although I work everyday with python on an advanced level your videos make me feel like I didn't know anything. I really like your videos since it seems like they are the only resource constantly delivering pro level python tutorials.
@@mCoding One question: Why did you call object.new in your last example instead of super().new like the examples before. Does this make any difference? As far as I undestand it would make a difference if your Base class iwould inherit something from another class, right?
Another banger, as we've come to expect at this point :) I remember reading the documentation on this but the only thing that stuck was the fact new creates the class and runs before init - what that actually meant or what I could do with it I had no idea, but changed this! Great video
Brilliant video. You are one of the very few programming channels which are presenting stuff which helps you move from a beginner software developer, to an intermediate one.
I spent hours on internet, this is the only video/blog explain clearly about __new__ and __ini__ !! Especially the part about when we need to modify __new__(). Thank you so much!!
In the Singleton example, do you not have the problem that __init__() will be called multiple times? If __init__() does anything non-trivial, this could be a huge problem. Or does overriding __new__() mean that __init__() might not get called? But that's not what it looks like at 1:20
The code at 1:20 gets called every time someone does Singleton(), so indeed every time you call this, the init will be called, and hence if new is returning a single instance the init will be called on the same object as many times as Singleton() is written. Therefore, if you use the singleton pattern this way, your init should either be empty or at least not modify the object. Most builtin types either have any empty new or an empty init.
The comment I made about Factory pattern was meant to apply to all the creational patterns in this video! The main intent of overriding new is subclassing builtin (or C extension) immutable types.
Exactly!! While watching @mcoding videos, I feel like I need atleast 2 years of experience in Python, but when I look at the general knowledge about the understanding of Python in companies and market, there is a big difference 😂
oh man - the awkward pause to subscribe was GOLD. these vids are great - I didn't know about the __new__ method - I'm intrigued! Sincerely, -new subscriber
Dude you're amazing, I've never seen anyone cover python at the level you do. Amazing detailing and explanations. Also , quick and easy to watch! Great stuff! 👍
Had I not seen this last year, today I would have fumbled around with __init__, not understanding what I was doing, and it would have cost me hours. Cheers for another top shelf lesson in the finer points of Python
9:20 This is actually perfect for a mini-feature I wanted to implement previously (generating a complete list of classes that all derive from the same base class). I still have to manually import all these classes, but at least I can now dynamically generate the list based on imports (I presume) instead of manually editing a list.
It's useful because init subclass will be inherited across multiple levels so you don't need to recursively track children, they just automatically call init subclass anyway!
Another great video, James! You're the only one in UA-cam that I found that covers advanced Python topics in a simple and clear manner! Could I request a topic for a video? I never quite understood how can I bundle C code in a Python package like Numpy does, for example. Could you cover that topic in a future video? Thank you for sharing your knowledge!
I tend to never subscribe to a channel as a response to being asked... But this was both sneaky and fun so now there's an exception to that rule. Also thanks for the clear and concise videos!
1:58 Actually, reading the documentation gives that it is a static method that takes the class of the instance as arguments. So that we can do A.__new__(A, args)
This is very useful for helping people learn about what happens when an object is being created. Nice examples of when to specify your own new method! Great material!! 😁
Ive never learn so much with just one python video You are awesomeeeee, the múltiple examples reaaaally make things way easier to understand and the performace tips are very intresting and usefull
I just want to let you know that this channel is basically single-highhandedly teaching me all of the 'advanced' python techniques/knowledge I know. Obviously I do my own research as well, but there are a lot of things that you just can't look up if you don't know they exist.
Really cool! The singleton pattern was the first thing that came to mind for me when I learned about the __new__() method. However, there is a small problem that other languages don't have. When you return the an instance in __new__(), __init__() will ALWAYS be called (if the type returned is correct). This means that in the singleton pattern, whenever you use the constructor to get the existing instance, it will be reinitialized, unless you explicitly add a check at the start of your implementation so it is only initialized once. Here is an example of a complete implementation of the singleton pattern circumventing that issue: ``` class Singleton: __instance = None __initialized = False def __new__(cls): if cls.__instance is None: cls.__instance = super(Test, cls).__new__(cls) return cls.__instance def __init__(self): # Check if the class has been initialized if self.__initialized: return # Mark the class as initialized, so that the initialization code # doesn't run more than once when the class is instantiated again self.__initialized = True # Actual initialization code self.attr = 1 ```
The EncryptedFile example reminded me of an Abstract class implementation. I'm not sure if python supports abstract classes the way other languages do, but this reminded me of it.
python supports abstract classes in a kinda unusual way. You need to use an abc module and do something like this: from abc import ABC, abstractmethod class Abstract(ABC): @abstractmethod def someMethod(): pass This essentially makes it so you can't create an instance of an abstract class and any class inheriting from it has to define all methods marked as abstract or else it'll cause a TypeError when you try to create an instance of a derived class.
I create classes with static and class methods, then create dunder new to make the class behave like a function. My colleagues don't like it, but I find it quite useful for splitting large functions.
@@senyai Oh okay so you are basically splitting you function up and encapsulate everything inside this modified class to only expose the first function?
an annoying issue with the singleton/caching use case is it will call __init__ on your pre-existing object every time, essentially making __init__ unusable, which can be a rather unfortunate gotcha. In these cases it's almost always more clear to use a function/classmethod instead, and maybe use a different language feature to prevent __init__ from being called nakedly.
I've been trying to find a good definition of what subclassing entails in python for the last couple of months. I now understand the distinction vs e.g. subclassing a window's render hooks in COM. Thanks!
The main topic of this video was definitely interesting, but at 6:30, I learned that you can make an f string print the expression as well as the evaluation by adding an = inside the curly braces. Now I'll need to actually read the documentation on f strings to see if there are any other special bits like that. I just thought it looked at the content of braces, evaluated them, concatenated the string, and then printed it, but apparently it does a lot more than that, since {x is y =} should give a syntax error. EDIT: and now I see that you have a video on that very topic. Watching now.
I love the encrypted file example. The only problem I see is that such methods basically destroy code completion. This can make using such frameworks very difficult.
Since each of the encrypted file classes inherits from EncryptedFile, code completion of the read method or any other methods in EncryptedFile should still work just fine. If you care to access implementation details of the subclasses, then this pattern is not the right choice, as it is meant to hide the details and just present the interface.
Well it seems like an easy mistake to make to keep the init method when using the Singleton pattern, which would result in init being called every time the Singleton is "recreated"
Indeed, if you use the singleton pattern this way, your init should either be empty or at least not modify the object. Most builtin types either have any empty new or an empty init.
Never new Python has a __new__ method. Something it doesn't make much sense to me is the return statement. I.e in the singleton example, when there's no previous singleton, you return "super().__new__(cls,*args,**kwars)" doesn't that make the method call it self in an endless recursion loop?
"super" refers to the parent class of the current class, which in this case would be "Object". The __new__ method of this class wouldn't have this conditional statement and would instead just return an instance of cls with the args assigned.
I have rediscovered new several times, each in the context of caching objects that are singletons, as in it only ever makes sense to have one instance with a given input. Note: these were all little math puzzles or personal projects, I wouldn't ever touch new in any serious context without a lot of thought and if there was really no other solution. It's not trivial to test, and it definitely goes against common practice.
As someone who isn't really familiar with factory pattern, it'd be cool to see how that last example would be better implemented using factory pattern instead
Thank you for another great video. The comment mentioning that a singleton has the same issue as a global variable misses the point of a singleton. A singleton is only used when, by design, only one instance is desired. Usually this is a poor design choice, but not always. There are some cases where only one item of a given type should exist. I agree about using the Factory patter. The book, "Design Patterns" changed the way I design code. I knew some of the contexts. That book provided a way to think and communicate design ideas.
5:23 Actually, the purpose of the singleton was not that there should be one of them. Really, the idea behind singleton was different - and smart! (kind of). You are surely familar with idea of classes like `Math.max()`, `Math.min()` - things that are static methods. Well, what would happen, if you needed to parametrize somehow the base of those methods? Well, by definition there isn't any, so we had to workaround it by returning object. Early examples of singleton patter were something like this: `Math.getInstance().max()`, and `Math.getInstance().min()`. Singleton's purpose was to allow editing static methods (so to speak). It's idea was never to "make object be instantiated once". That was never it intent - it was a consequence - there could only ever be one instance, since that's all you could fit into a static method. To have only one instance of a class, you don't need singleton - just create one instance of it, and you're done.
These are called metaclass keyword arguments. www.python.org/dev/peps/pep-3115/#specification It passes the keyword arguments to many functions that the metaclass calls when instantiating the class.
First, Thanks In addition, all the use cases that you showed can be implemented using simple features of python without "new" or "init_subclass" (and you say this in the Singleton example). So, I assume that it only for teaching and explains.
Awesome video, thank you. Quick Q. At 1:43 you demonstrated that init will not be called if the is instance(x, A) does not identify x as an object of type A. However later Encrypted file example you are returning subclass objects. Why will this not fail as is instance will identify them as a subclass type, not the type of the class itself, thus not running init? Hope that question makes sense.
Thanks for the content!! Do we consider the Encryption sample as strategy pattern? And I think my question is that, what is the benefit implementing in this way comparing with passing different encryption method into a third class?
Thumbs up for how clearly you explain these things, however I do feel as there could have been more examples on subclassing immutable data types and restricting their domain. Say if you want to make a class for natural numbers that inherits from int, or a string that's strictly an email address. Doing validation at the type level encourages the "parse, don't validate" design pattern, that I personally think we could use more of.
I think it is really dangerous to keep the clients cache as a class variable. If you deploy this code to for example Azure functions, the cache is not cleared in between separate runs even though 99 % of people would think it is. I would suggest having the cache as a separate variable, which initialization and reinitialization is more under control.
Hi, this code is for educational purposes of how you can use __new__, not production use. I try to give minimal examples so that viewers can understand the topic at hand rather than dig through hundres or thousands of lines of unrelated code. As with any cache in a production environment, it may be beneficial to limit its size or otherwise expire its data in a timely fashion. If you are looking for an example of something like this in full fledged production form with all the bells and whistles, I'd recommend reading SQLAlchemy's source code.
Could you please make a series going over the OOP concepts in python (newest version) from scratch, covering every detail ever, an updated version. That'd be really helpful !
Could you share about becoming master in python.. I'm an intermediate still unable to understand your video quickly it's really above master level how you are getting this much knowledge?
This chanel has a very high python value. It's nothing like the others, recycling docummentation or from one another. You can easilly see this on the file examples, where there are codecs and itertools correctly used.
I'm happy that my viewers can see and appreciate everything I put into the videos! Thanks for being an awesome viewer!
Yes I like this channel for quick examples of certain features and learning why things are the way they are and what you can do with those features. For software architecture and design patterns I like Arjan Codes. Especially the innovative code roasts series
Absolutely, you are quite literally the only person I have clicked the notification bell for. Top notch content, keep it up!
Yeah, everybody else for this language has one of a few gimmicks running. Selling entry level courses, covering some thing with a crummy library under the clickbait premise that its a smart to thing to learn because it uses “so few lines of code”, or, well, intermediate level courses.
Almost no explaining builtins and patterns.
Quite useful when I want to know something. Straight, to the point. I still think it’s funny that I went: time to learn python to make a quadratic cracker despite having no experience in non block coding, and after a summer, I am now ok at python!
Decrypted message zoom in was priceless.
As usual, excellent video.
Thank you very much, glad you enjoyed it :)
@@mCoding Love your videos. Finally subscribed, that zoom in was well done.
@@mCoding yea, may I ask why you chose those TERRIBLE encryption algorithms
@@rogervanbommel1086 I'm assuming so that people wouldn't try to use his code for actual encryption and blame him if things went wrong?
@@rogervanbommel1086 what do you mean? he used the only mathematically proven unbreakable encryption algorithm
I really like how you get straight to the point and give clear and concise explanations. This channel is one of the best if not the the best resource for understanding more difficult concepts in python.
I didn't even know __new__ was a thing until seeing this video. I've always used __init__ and that's what I've seen other people always do as well.
Completely understandable, you can go your whole life and never actually need to override new, but init obviously is needed all the time.
Quality content, yet again. Idiomatic Python, concise explanations, nothing less. 11/10
thanks shrek
Nice video! That last point really highlighted where I might personally use __new__ in my own projects, really insightful video!
Great to hear!
Excellent, just as always! The Python level you teach is just another level. Love your videos.
Can you do a tutorial on super function as well? I would really appreciate that.
Yes, that would be good, especially in the case of multiple inheritance. Actually, the do's-and-don't's of multiple inheritance in general would be great
This channel is the only one on UA-cam that actually showcases unique and interesting stuff and doesn't just read out the iter-tools docs.
Many thanks for the kind words. I love reading itertools docs :)
Man your videos are awesome. I like that they are so much on point without artifical fluff to make them unnecessarily longer. Every video has one topic and sticks to it similar to "a function should do one job only" :). Great job!
Hi, I really like your videos and they always help me understand something i didn't know in python! Thank you!
Happy to hear that!
I love those videos where you look at one single issue and explain it in-depth! while all of those videos may already exist on yt, most are just not as well made. yours are a joy to watch!
So glad to hear your kind words! Thanks!
The value of a singleton is when you need an abstraction to something where there is an actual constraint that "there can be only one". The classic example is hardware access. Suppose you open a connection to a device that only supports a single connection (e.g. a COM port), and a set of objects that can access that device. Making the device abstraction a singleton is a great design pattern. Any object can instantiate the device object. If it's the first one, a new object is instantiated. If it's a subsequent construction, the object gets a reference to the already instantiated device.
Holy shit, although I work everyday with python on an advanced level your videos make me feel like I didn't know anything. I really like your videos since it seems like they are the only resource constantly delivering pro level python tutorials.
You're welcome! Keep watching and you'll learn all the stuff too!
@@mCoding One question: Why did you call object.new in your last example instead of super().new like the examples before. Does this make any difference? As far as I undestand it would make a difference if your Base class iwould inherit something from another class, right?
I'd like to recommend the channel AnthonyWritesCode. The guy behind it maintains Tox, Flake8, and DeadSnakes.
Man I'm just so happy that such high quality content is for free. Greetings from Germany!
Another banger, as we've come to expect at this point :)
I remember reading the documentation on this but the only thing that stuck was the fact new creates the class and runs before init - what that actually meant or what I could do with it I had no idea, but changed this! Great video
Brilliant video. You are one of the very few programming channels which are presenting stuff which helps you move from a beginner software developer, to an intermediate one.
I spent hours on internet, this is the only video/blog explain clearly about __new__ and __ini__ !! Especially the part about when we need to modify __new__(). Thank you so much!!
In the Singleton example, do you not have the problem that __init__() will be called multiple times? If __init__() does anything non-trivial, this could be a huge problem. Or does overriding __new__() mean that __init__() might not get called? But that's not what it looks like at 1:20
The code at 1:20 gets called every time someone does Singleton(), so indeed every time you call this, the init will be called, and hence if new is returning a single instance the init will be called on the same object as many times as Singleton() is written. Therefore, if you use the singleton pattern this way, your init should either be empty or at least not modify the object. Most builtin types either have any empty new or an empty init.
The last example seems like it would be done more simply with a factory pattern too
The comment I made about Factory pattern was meant to apply to all the creational patterns in this video! The main intent of overriding new is subclassing builtin (or C extension) immutable types.
You always makes me feel like I know nothing in python😄😄. I really like this channel.
Exactly!!
While watching @mcoding videos, I feel like I need atleast 2 years of experience in Python, but when I look at the general knowledge about the understanding of Python in companies and market, there is a big difference 😂
@@ashishjain518 😄😄
Finally someone explained this, so many people call __init__ a constructor.
init is constructor of the object
new is constructor of the bases :/
@@NoNameAtAll2 I would disagree , considering definition of the class constructor.
oh man - the awkward pause to subscribe was GOLD.
these vids are great - I didn't know about the __new__ method - I'm intrigued!
Sincerely,
-new subscriber
After many years of daily use, I thought I new everything about python. Your videos never fail to prove otherwise. Thanks for the excellent content!
Dude you're amazing, I've never seen anyone cover python at the level you do. Amazing detailing and explanations. Also , quick and easy to watch! Great stuff! 👍
I learned something new! (__init_subclass__)
Thanks!
This is a great channel!
I always wondered why the heck we use 'self' in the __init__ method. Now I know! Thanks for this informative video, it helped alot!
Caching clients is a super practical example. I've used this technique numoirous times in production code.
Had I not seen this last year, today I would have fumbled around with __init__, not understanding what I was doing, and it would have cost me hours. Cheers for another top shelf lesson in the finer points of Python
Today I learnt about ```__new__```. But I also learnt about ```print(f'{EXPRESSION=}')``` That '=' at the end is rly neat
He covered that in another video. He has great content!
I am always learning new stuff here, you are awesome! thank you for these contents. They really help us a lot.
Happy to hear that!
9:20 This is actually perfect for a mini-feature I wanted to implement previously (generating a complete list of classes that all derive from the same base class). I still have to manually import all these classes, but at least I can now dynamically generate the list based on imports (I presume) instead of manually editing a list.
These videos are all those questions you Google and find answers to on stack overflow.
Excellent video! I have never used __new__ myself, but would consider it now- very well explained, thanks!
Nice video! The examples are really appreciated.
Glad it was helpful!
This might be the only programming channel that I'm seriously considering binging the content of
Great content as always. Going to use the EncryptedFile example instead of a proxy class in my code.
Saving this for later. I think I can use that init subclass pattern at work
It's useful because init subclass will be inherited across multiple levels so you don't need to recursively track children, they just automatically call init subclass anyway!
Another great video, James! You're the only one in UA-cam that I found that covers advanced Python topics in a simple and clear manner!
Could I request a topic for a video? I never quite understood how can I bundle C code in a Python package like Numpy does, for example. Could you cover that topic in a future video?
Thank you for sharing your knowledge!
Thanks! C extensions are on my list don't worry!
I loved the look at the end saying "take the hint" xD
Insanely great! Thanks for your work!
This channel is so good for me who bury them self into python
a lot of details about how python work and pythonic technique
Love!
You're one of the most if not the most underrated programming channel on UA-cam.
I tend to never subscribe to a channel as a response to being asked... But this was both sneaky and fun so now there's an exception to that rule. Also thanks for the clear and concise videos!
I've been using Python for a decade and I never ___new___ this!
1:58 Actually, reading the documentation gives that it is a static method that takes the class of the instance as arguments. So that we can do A.__new__(A, args)
This is very useful for helping people learn about what happens when an object is being created. Nice examples of when to specify your own new method! Great material!! 😁
Ive never learn so much with just one python video
You are awesomeeeee, the múltiple examples reaaaally make things way easier to understand and the performace tips are very intresting and usefull
Really loving this channel, always finding new ways to do things. Thank you!
I'm always finding init ways to do things!
I just want to let you know that this channel is basically single-highhandedly teaching me all of the 'advanced' python techniques/knowledge I know. Obviously I do my own research as well, but there are a lot of things that you just can't look up if you don't know they exist.
Great to hear :) glad you enjoyed my videos!
Really cool! The singleton pattern was the first thing that came to mind for me when I learned about the __new__() method. However, there is a small problem that other languages don't have.
When you return the an instance in __new__(), __init__() will ALWAYS be called (if the type returned is correct). This means that in the singleton pattern, whenever you use the constructor to get the existing instance, it will be reinitialized, unless you explicitly add a check at the start of your implementation so it is only initialized once. Here is an example of a complete implementation of the singleton pattern circumventing that issue:
```
class Singleton:
__instance = None
__initialized = False
def __new__(cls):
if cls.__instance is None:
cls.__instance = super(Test, cls).__new__(cls)
return cls.__instance
def __init__(self):
# Check if the class has been initialized
if self.__initialized:
return
# Mark the class as initialized, so that the initialization code
# doesn't run more than once when the class is instantiated again
self.__initialized = True
# Actual initialization code
self.attr = 1
```
You could also override the dunder call on the metaclass so avoid this issues.
The EncryptedFile example reminded me of an Abstract class implementation. I'm not sure if python supports abstract classes the way other languages do, but this reminded me of it.
python supports abstract classes in a kinda unusual way. You need to use an abc module and do something like this:
from abc import ABC, abstractmethod
class Abstract(ABC):
@abstractmethod
def someMethod():
pass
This essentially makes it so you can't create an instance of an abstract class and any class inheriting from it has to define all methods marked as abstract or else it'll cause a TypeError when you try to create an instance of a derived class.
I always learn something intimidatingly new here thanks for the video.
After this video.. I still have lot of things to learn in Python. This is such a quality video. Thank you.
Thanks for showing me the existence of ___init_subclass___
Very welcome!
I didn't even know __new__ existed, seems really niche, but potentially useful
I create classes with static and class methods, then create dunder new to make the class behave like a function. My colleagues don't like it, but I find it quite useful for splitting large functions.
How do you mean this? What are the class methods for if your dunder new just acts like a normal function?
@@comedyclub333 For example: `def _ _ new _ _(cls, a, b): return cls._f2(cls._f1(a), b)`
@@senyai Oh okay so you are basically splitting you function up and encapsulate everything inside this modified class to only expose the first function?
> My colleagues don't like it
I wonder why 🤔
Great as always. I'm really looking forward to the meta class video, I never really got those.
The uppercase tuple is great candidate for a coding challenge. I'll use it on my colleagues.
Roast them then make sure to share the vid with them afterwards :)
an annoying issue with the singleton/caching use case is it will call __init__ on your pre-existing object every time, essentially making __init__ unusable, which can be a rather unfortunate gotcha. In these cases it's almost always more clear to use a function/classmethod instead, and maybe use a different language feature to prevent __init__ from being called nakedly.
But if you don’t put anything in your init method, then it will do nothing. Put all the object setup in the new method instead.
Thank you James, great explanation!
I've been trying to find a good definition of what subclassing entails in python for the last couple of months. I now understand the distinction vs e.g. subclassing a window's render hooks in COM. Thanks!
Again a very high quality video! Thanks a lot
that's high quality info right there!!
The presence of "self" in the init signature should give away the fact that the instance already exists when the init is called
Quite Fascinating, how adding a = to a print statement would calculate the value as well.
i need a complete course from this channel.
Great one! This is really high quality content! Can't wait for the video on metaclasses
The main topic of this video was definitely interesting, but at 6:30, I learned that you can make an f string print the expression as well as the evaluation by adding an = inside the curly braces.
Now I'll need to actually read the documentation on f strings to see if there are any other special bits like that. I just thought it looked at the content of braces, evaluated them, concatenated the string, and then printed it, but apparently it does a lot more than that, since {x is y =} should give a syntax error.
EDIT: and now I see that you have a video on that very topic. Watching now.
I have a feeling you will enjoy a lot of my videos :)
So good, glad I found your channel
Great video!
But I did not understand the drawback of a singleton? Isn't your client example a Singleton too?
Subscribing right after the zoom in :P
I needed this, thank you!
Discord gang
🤚
👋
I love the encrypted file example. The only problem I see is that such methods basically destroy code completion. This can make using such frameworks very difficult.
i dont think so. if the subclasses all implement the same methods as the parent this should be fine.
Since each of the encrypted file classes inherits from EncryptedFile, code completion of the read method or any other methods in EncryptedFile should still work just fine. If you care to access implementation details of the subclasses, then this pattern is not the right choice, as it is meant to hide the details and just present the interface.
I think you are right. Used in that way it makes total sense. Now I see how it comes together.
Singletons are also super hard to test because of tight coupling and difficulty to mock in tests.
channel is underrated!
Well it seems like an easy mistake to make to keep the init method when using the Singleton pattern, which would result in init being called every time the Singleton is "recreated"
Indeed, if you use the singleton pattern this way, your init should either be empty or at least not modify the object. Most builtin types either have any empty new or an empty init.
Just WOW. I didn't know a thing before, and now I know that I didn't know, unfortunately I still don't know.
Please make more videos about design patterns and the context in which they are best used.
Never new Python has a __new__ method. Something it doesn't make much sense to me is the return statement. I.e in the singleton example, when there's no previous singleton, you return "super().__new__(cls,*args,**kwars)" doesn't that make the method call it self in an endless recursion loop?
"super" refers to the parent class of the current class, which in this case would be "Object". The __new__ method of this class wouldn't have this conditional statement and would instead just return an instance of cls with the args assigned.
I have rediscovered new several times, each in the context of caching objects that are singletons, as in it only ever makes sense to have one instance with a given input.
Note: these were all little math puzzles or personal projects, I wouldn't ever touch new in any serious context without a lot of thought and if there was really no other solution. It's not trivial to test, and it definitely goes against common practice.
As someone who isn't really familiar with factory pattern, it'd be cool to see how that last example would be better implemented using factory pattern instead
Thank you for another great video.
The comment mentioning that a singleton has the same issue as a global variable misses the point of a singleton. A singleton is only used when, by design, only one instance is desired. Usually this is a poor design choice, but not always. There are some cases where only one item of a given type should exist.
I agree about using the Factory patter. The book, "Design Patterns" changed the way I design code. I knew some of the contexts. That book provided a way to think and communicate design ideas.
Who were the authors of the book?
5:23 Actually, the purpose of the singleton was not that there should be one of them. Really, the idea behind singleton was different - and smart! (kind of).
You are surely familar with idea of classes like `Math.max()`, `Math.min()` - things that are static methods. Well, what would happen, if you needed to parametrize somehow the base of those methods? Well, by definition there isn't any, so we had to workaround it by returning object. Early examples of singleton patter were something like this: `Math.getInstance().max()`, and `Math.getInstance().min()`. Singleton's purpose was to allow editing static methods (so to speak). It's idea was never to "make object be instantiated once". That was never it intent - it was a consequence - there could only ever be one instance, since that's all you could fit into a static method. To have only one instance of a class, you don't need singleton - just create one instance of it, and you're done.
Great video, bump for algorithm
Much appreciated!
at 9:30, what does prefix="rot13" do? Are you extending from two classes EncryptedFiles and prefix? Not sure what prefix is. Thanks.
These are called metaclass keyword arguments. www.python.org/dev/peps/pep-3115/#specification
It passes the keyword arguments to many functions that the metaclass calls when instantiating the class.
First, Thanks
In addition, all the use cases that you showed can be implemented using simple features of python without "new" or "init_subclass" (and you say this in the Singleton example).
So, I assume that it only for teaching and explains.
Awesome video, thank you.
Quick Q.
At 1:43 you demonstrated that init will not be called if the is instance(x, A) does not identify x as an object of type A.
However later Encrypted file example you are returning subclass objects. Why will this not fail as is instance will identify them as a subclass type, not the type of the class itself, thus not running init?
Hope that question makes sense.
A subclass IS and instance of the super class, so the instance check will pass. Hope this helps!
Thanks for the content!! Do we consider the Encryption sample as strategy pattern? And I think my question is that, what is the benefit implementing in this way comparing with passing different encryption method into a third class?
Thumbs up for how clearly you explain these things, however I do feel as there could have been more examples on subclassing immutable data types and restricting their domain. Say if you want to make a class for natural numbers that inherits from int, or a string that's strictly an email address. Doing validation at the type level encourages the "parse, don't validate" design pattern, that I personally think we could use more of.
I think it is really dangerous to keep the clients cache as a class variable. If you deploy this code to for example Azure functions, the cache is not cleared in between separate runs even though 99 % of people would think it is. I would suggest having the cache as a separate variable, which initialization and reinitialization is more under control.
Hi, this code is for educational purposes of how you can use __new__, not production use. I try to give minimal examples so that viewers can understand the topic at hand rather than dig through hundres or thousands of lines of unrelated code. As with any cache in a production environment, it may be beneficial to limit its size or otherwise expire its data in a timely fashion. If you are looking for an example of something like this in full fledged production form with all the bells and whistles, I'd recommend reading SQLAlchemy's source code.
Mind = Blown. Amazing stuff
In many cases a class where all its functions are static seems quite singleton.
took me a while due to mistake, but it works thanks
u a monster man, love your videos
Thanks for the love, I appreciate it!
Amazing content. Learning so much 😌
Could you please make a series going over the OOP concepts in python (newest version) from scratch, covering every detail ever, an updated version. That'd be really helpful !
he looks like almond flavored lawyer jerma
Every time I see your video I think to myself "damn this would be very useful for my work!" lol.
Could you share about becoming master in python.. I'm an intermediate still unable to understand your video quickly it's really above master level how you are getting this much knowledge?