what is a singleton? (and python patterns) (intermediate - advanced) anthony explains #188

preview_player
Показать описание
today I talk about the singleton pattern and a bunch of different ways to implement it in python!

==========

I won't ask for subscriptions / likes / comments in videos but it really helps the channel. If you have any suggestions or things you'd like to see please comment below!
Рекомендации по теме
Комментарии
Автор

I really enjoy your content. Your love for programming is very evident and it's contagious. Thank you so so much.

chukwunta
Автор

Watching you code just leaves me at awe... Truly an inspiration!

UriYakir
Автор

You are a rare gem. I have encountered such problems before, thanks alot for this video. Love from Nigeria.

tombraril
Автор

I am very much enjoying your videos. Keep up the good work Anthony!

bojandimic
Автор

Here's how i would do it:

from weakref import WeakValueDictionary


class Singleton(type):
_instances = WeakValueDictionary()

def __call__(cls, *args, **kwargs):
try:
return type(cls)._instances[cls]
except KeyError:
obj = type(cls)._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return obj

@classmethod
def cache_size(mcs):
return len(mcs._instances)


class Foo(metaclass=Singleton):
def __init__(self):
self.x = 1

def do_stuff(self):
return self.x + 1


obj1 = Foo()
obj2 = Foo()

print(obj1 is obj2) # True
print(f"Objects in cache: {Singleton.cache_size()}") # 1

del obj1
del obj2

print(f"Objects in cache: {Singleton.cache_size()}") # 0

patskanteam
Автор

Thanks for all the great content, I have always been enjoying taking them with my breakfast haha.

I have a question on something could be quite trivial that is not even the main point of this video. At 16:48, you rewrite your `if` statement into `try except`, why did you choose `try` over `if` in this particular case?

I have always been confused about when I should use `try` and when `if`, and a lot of times I find myself using `if` without the need of using `try`, and I can argue that a lot of times I could have used `try` instead. What is your general rule of picking one if the situation allows you to use either?

alsonyang
Автор

Is there a difference between type(self) and self.__class__?

tobb
Автор

Awesome video. Great tricks. Thank you

dorb
Автор

Sir plz share more about design patterns in python

bhushanmakode
Автор

Well if this wasn't a really great commentary of python's data model!

More patterns/idioms, please!

Автор

great video as always. saved me lots of headaches.

splendorman
Автор

I wonder - How do you come up and understand the internals of python so good? What do you do rather than read and write a lot of code. It's been a year since I watched this video last and I still can't make up a singleton code from my mind even though I work as software engineer.How do you know when to use cls.inst and when super().__new__(cls) - it feel to me that I could memorize the idea and code from your videos, but I would never know how to use cls for dunder functions such as __new__ or less familiar and used ones like it in order to solve the singleton design pattern of other ideas...

dorb
Автор

mind=pancake
This is some confusing stuff.
Seeing you write that metaclass taught me alot about how pythons classes work behind-the-scenes, I'm gonna do some more research on that.

I like python for it's "hackability", you can break the language right down and do all sorts of magic with it's internals.

goodclover
Автор

what about a practical, real-life-code-problem-solving, design patterns series?

talalkalai
Автор

Singleton is so cursed that at the end it broke anthony scene switcher! hahah

walkdead
Автор

More patterns and design infrastructure please

yaron-ehsass
Автор

For me singelton or global state is indication that i made something wrong with architecture ot thought process, i avoid it with any cost! But grate video!

MichalPlichta
Автор

class Singleton:
__instance = None

def __new__(cls):
if Singleton.__instance == None:
Singleton.__instance = super().__new__(cls)
return Singleton.__instance

database = Singleton()
database.x = 8
print(database.x)
database2 = Singleton()
print(database2.x)

kvelez