{"id":118,"date":"2020-11-29T06:58:33","date_gmt":"2020-11-29T06:58:33","guid":{"rendered":"http:\/\/www.kowanas.com\/coding\/?p=118"},"modified":"2022-07-06T11:08:11","modified_gmt":"2022-07-06T11:08:11","slug":"singleton-pattern","status":"publish","type":"post","link":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/","title":{"rendered":"Start Python #1 Thread safe singleton pattern"},"content":{"rendered":"\n<p>The singleton pattern ensures class has only one instance, and provides a global point of access to it. <sup><a href=\"#footnote_0_118\" id=\"identifier_0_118\" class=\"footnote-link footnote-identifier-link\" title=\"Freeman Robson, Head First Design Patterns, O&rsquo;REILLY, 2014, p179\">1<\/a><\/sup><\/p>\n\n\n\n<p>You can see an example code from <a href=\"https:\/\/youtu.be\/9HE_oG4feao\">this video<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">singleton pattern<\/h2>\n\n\n\n<p>It&#8217;s one of design pattern described by GOF (Gang of Four).<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png\" alt=\"singleton pattern class diagram\" class=\"wp-image-122\" width=\"267\" height=\"149\"\/><\/figure>\n\n\n\n<p>There are many objects we only need one.<\/p>\n\n\n\n<p>In example, There are such as device driver, data repository and logging.<\/p>\n\n\n\n<p>I always use Singleton rather than a global variable because the code in my project is much more concise.<\/p>\n\n\n\n<p>This chapter explains how to implement singleton pattern with python with example code.<\/p>\n\n\n\n<p>And I designed it to be thread safe because I sometimes use multi treading in python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Singleton.py<\/h2>\n\n\n\n<p>I made <code>Sington<\/code> type which is able to create and hold an instance.<\/p>\n\n\n\n<p>Please refer this <a href=\"https:\/\/blog.ionelmc.ro\/2015\/02\/09\/understanding-python-metaclasses\/\">page<\/a> if you want to understand <code>metaclass<\/code> and <code>type<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from threading import Lock\n\nclass Singleton(type):\n    _instance = None\n    _lock = Lock()\n\n    def __call__(cls, *args, **kwargs):\n        with cls._lock:\n            if not cls._instance:\n                cls._instance = super().__call__(*args, **kwargs)\n        return cls._instance<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">SingletonClass.py<\/h2>\n\n\n\n<p>This is an sample Singleton class to hold variables and to provide interfaces.<\/p>\n\n\n\n<p>This <code>SingletonClass<\/code> has a <code>name<\/code> variable that is set when class is instantiated.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from Singleton import Singleton\nfrom threading import Thread\n\nclass SingletonClass(metaclass=Singleton):\n    def __init__(self, name):\n        self.name = name\n\ndef run(value):\n    singleton = SingletonClass(value)\n    print(singleton.name)\n\nif __name__ == '__main__':\n    processa = Thread(target=run, args=('ACLASS',))\n    processb = Thread(target=run, args=('BCLASS',))\n    processa.start()\n    processb.start()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Test Result<\/h2>\n\n\n\n<p>I created 2 threads calling of each <code>SingletonClass(value)<\/code>. <\/p>\n\n\n\n<p>Even if you call <code>SingletonClass<\/code> with <code>'BCLASS'<\/code> as the <code>name<\/code>, both objects show the <code>name<\/code> of the object created at first.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ACLASS\nACLASS<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">What is the <code><strong>Start Python<\/strong><\/code> series<\/h2>\n\n\n\n<p>Most beginners start programming by printing &#8216;Hello world!&#8217; and learning the syntax, but we know that a project requires more things.<br>So, I would like to introduce a code snippet what I met in my actual project.<\/p>\n\n\n\n<p>I will not use framework such as Django because people have difference environment and use cases.<\/p>\n\n\n\n<p>Please let me know if you need further information about this article.<\/p>\n<ol class=\"footnotes\"><li id=\"footnote_0_118\" class=\"footnote\">Freeman Robson, Head First Design Patterns, O&#8217;REILLY, 2014, p179<span class=\"footnote-back-link-wrapper\"> [<a href=\"#identifier_0_118\" class=\"footnote-link footnote-back-link\">&#8617;<\/a>]<\/span><\/li><\/ol>","protected":false},"excerpt":{"rendered":"<p>The singleton pattern ensures class has only one instance, and provides a global point of access to it. 1 You can see an example code from this video. singleton pattern It&#8217;s one of design pattern described by GOF (Gang of Four). There are many objects we only need one. In example, There are such as &#8230; <a title=\"Start Python #1 Thread safe singleton pattern\" class=\"read-more\" href=\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\" aria-label=\"Read more about Start Python #1 Thread safe singleton pattern\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23],"tags":[25,26],"class_list":["post-118","post","type-post","status-publish","format-standard","hentry","category-programming","tag-python","tag-singleton"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Start Python #1 Thread safe singleton pattern - Kowana&#039;s coding<\/title>\n<meta name=\"description\" content=\"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Start Python #1 Thread safe singleton pattern - Kowana&#039;s coding\" \/>\n<meta property=\"og:description\" content=\"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\" \/>\n<meta property=\"og:site_name\" content=\"Kowana&#039;s coding\" \/>\n<meta property=\"article:published_time\" content=\"2020-11-29T06:58:33+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-07-06T11:08:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png\" \/>\n<meta name=\"author\" content=\"kowana\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"kowana\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\",\"url\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\",\"name\":\"Start Python #1 Thread safe singleton pattern - Kowana's coding\",\"isPartOf\":{\"@id\":\"https:\/\/www.kowanas.com\/coding\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png\",\"datePublished\":\"2020-11-29T06:58:33+00:00\",\"dateModified\":\"2022-07-06T11:08:11+00:00\",\"author\":{\"@id\":\"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/190c7dff713254da763d4fe295be98af\"},\"description\":\"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage\",\"url\":\"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png\",\"contentUrl\":\"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.kowanas.com\/coding\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Start Python #1 Thread safe singleton pattern\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/#website\",\"url\":\"https:\/\/www.kowanas.com\/coding\/\",\"name\":\"Kowana's coding\",\"description\":\"\ucc9c\ucc9c\ud788 \ud55c\uac78\uc74c\uc529 \ud55c\uac78\uc74c\uc529 \ucf54\ub529\uc774 \ub300\uc138\ub780\ub2e4 \uc544\ub4e4\uc544\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.kowanas.com\/coding\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/190c7dff713254da763d4fe295be98af\",\"name\":\"kowana\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/80a89adb37a55d376afb969e327758fb?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/80a89adb37a55d376afb969e327758fb?s=96&d=mm&r=g\",\"caption\":\"kowana\"},\"url\":\"https:\/\/www.kowanas.com\/coding\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Start Python #1 Thread safe singleton pattern - Kowana's coding","description":"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/","og_locale":"en_US","og_type":"article","og_title":"Start Python #1 Thread safe singleton pattern - Kowana's coding","og_description":"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.","og_url":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/","og_site_name":"Kowana's coding","article_published_time":"2020-11-29T06:58:33+00:00","article_modified_time":"2022-07-06T11:08:11+00:00","og_image":[{"url":"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png","type":"","width":"","height":""}],"author":"kowana","twitter_card":"summary_large_image","twitter_misc":{"Written by":"kowana","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/","url":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/","name":"Start Python #1 Thread safe singleton pattern - Kowana's coding","isPartOf":{"@id":"https:\/\/www.kowanas.com\/coding\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage"},"image":{"@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage"},"thumbnailUrl":"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png","datePublished":"2020-11-29T06:58:33+00:00","dateModified":"2022-07-06T11:08:11+00:00","author":{"@id":"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/190c7dff713254da763d4fe295be98af"},"description":"There are many objects we only need one. This chapter explains how to implement singleton pattern with python with example code.","breadcrumb":{"@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#primaryimage","url":"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png","contentUrl":"https:\/\/www.kowanas.com\/coding\/wp-content\/uploads\/sites\/5\/2020\/11\/image-18.png"},{"@type":"BreadcrumbList","@id":"https:\/\/www.kowanas.com\/coding\/2020\/11\/29\/singleton-pattern\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.kowanas.com\/coding\/"},{"@type":"ListItem","position":2,"name":"Start Python #1 Thread safe singleton pattern"}]},{"@type":"WebSite","@id":"https:\/\/www.kowanas.com\/coding\/#website","url":"https:\/\/www.kowanas.com\/coding\/","name":"Kowana's coding","description":"\ucc9c\ucc9c\ud788 \ud55c\uac78\uc74c\uc529 \ud55c\uac78\uc74c\uc529 \ucf54\ub529\uc774 \ub300\uc138\ub780\ub2e4 \uc544\ub4e4\uc544","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.kowanas.com\/coding\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/190c7dff713254da763d4fe295be98af","name":"kowana","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.kowanas.com\/coding\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/80a89adb37a55d376afb969e327758fb?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/80a89adb37a55d376afb969e327758fb?s=96&d=mm&r=g","caption":"kowana"},"url":"https:\/\/www.kowanas.com\/coding\/author\/admin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/posts\/118","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/comments?post=118"}],"version-history":[{"count":9,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/posts\/118\/revisions"}],"predecessor-version":[{"id":479,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/posts\/118\/revisions\/479"}],"wp:attachment":[{"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/media?parent=118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/categories?post=118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kowanas.com\/coding\/wp-json\/wp\/v2\/tags?post=118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}