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

แชร์
ฝัง
  • เผยแพร่เมื่อ 26 ธ.ค. 2020
  • today I talk about the singleton pattern and a bunch of different ways to implement it in python!
    - typing Final: • python typing: Final /...
    - decorators: • python @decorators - (...
    - lru_cache: • python: functools.lru_...
    playlist: • anthony explains
    ==========
    twitch: / anthonywritescode
    dicsord: / discord
    twitter: / codewithanthony
    github: github.com/asottile
    stream github: github.com/anthonywritescode
    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!
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 28

  • @chukwunta
    @chukwunta 2 ปีที่แล้ว +6

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

  • @UriYakir
    @UriYakir 3 ปีที่แล้ว +8

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

  • @bojandimic3914
    @bojandimic3914 หลายเดือนก่อน

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

  • @tombra4ril
    @tombra4ril 3 ปีที่แล้ว +3

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

  • @patskanteam
    @patskanteam 3 ปีที่แล้ว +3

    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

  • @dorb1337
    @dorb1337 2 ปีที่แล้ว +2

    Awesome video. Great tricks. Thank you

  • @splendorman7922
    @splendorman7922 ปีที่แล้ว

    great video as always. saved me lots of headaches.

  • @bhushanmakode7643
    @bhushanmakode7643 2 ปีที่แล้ว +1

    Sir plz share more about design patterns in python

  •  3 ปีที่แล้ว +2

    Well if this wasn't a really great commentary of python's data model!
    More patterns/idioms, please!

  • @goodclover
    @goodclover 3 ปีที่แล้ว +6

    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.

    • @sadhlife
      @sadhlife 3 ปีที่แล้ว

      exactly :D python lets you hook into its internals pretty easily when needed

  • @yaronshamul2959
    @yaronshamul2959 2 ปีที่แล้ว

    More patterns and design infrastructure please

  • @walkdead94
    @walkdead94 2 ปีที่แล้ว

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

  • @alsonyang230
    @alsonyang230 ปีที่แล้ว

    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?

    • @anthonywritescode
      @anthonywritescode  ปีที่แล้ว +1

      in that case it's for performance -- make the common path fast. the pattern is called EAFP

    • @alsonyang230
      @alsonyang230 ปีที่แล้ว

      @@anthonywritescode Thanks for your reply!

  • @tobb10001
    @tobb10001 2 ปีที่แล้ว +2

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

    • @anthonywritescode
      @anthonywritescode  2 ปีที่แล้ว +1

      heheheh th-cam.com/video/6rAIttnm3Fs/w-d-xo.html

  • @talalkalai8748
    @talalkalai8748 2 ปีที่แล้ว

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

    • @anthonywritescode
      @anthonywritescode  2 ปีที่แล้ว +1

      I've done those in the past, they get really poor reception on youtube. my twitch streams are basically that though so maybe check those out!

  • @dorb1337
    @dorb1337 ปีที่แล้ว

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

  • @MichalPlichta
    @MichalPlichta 10 หลายเดือนก่อน

    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!

  • @kvelez
    @kvelez 8 หลายเดือนก่อน

    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)

  • @kuijaye
    @kuijaye 2 ปีที่แล้ว

    Apparently There's a guy named Anthony Singleton in one of the videos on youtube :)