{"id":79294,"date":"2020-07-06T11:30:39","date_gmt":"2020-07-06T06:00:39","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=79294"},"modified":"2020-07-06T11:30:39","modified_gmt":"2020-07-06T06:00:39","slug":"closures-in-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/","title":{"rendered":"Closures in Python with Examples"},"content":{"rendered":"<p>If you have been into programming for a while, chances are you might\u2019ve heard the word <strong>\u2018Closure\u2019<\/strong> in <strong>JavaScript<\/strong>. Turns out, <strong>closures<\/strong> are <strong>not limited<\/strong> to <strong>JavaScript<\/strong>.<\/p>\n<p><strong>Python<\/strong> offers <strong>support<\/strong> for <strong>closures<\/strong> too. In this article, we\u2019ll learn what closures in Python are, <strong>how to define<\/strong> them and lastly, <strong>when<\/strong>, and <strong>why you should use them<\/strong>.<\/p>\n<h3>What are Closures in Python?<\/h3>\n<p>Like <strong>nested loops<\/strong>, we can also <strong>nest functions<\/strong>. That said, Python gives us the <strong>power<\/strong> to define <strong>functions<\/strong> <strong>within functions<\/strong>.<\/p>\n<p>Python <strong>Closures <\/strong>are these<strong> inner functions <\/strong>that are<strong> enclosed within <\/strong>the <strong>outer function<\/strong>. Closures can <strong>access variables<\/strong> present in the <strong>outer function scope<\/strong>. It can <strong>access<\/strong> these <strong>variables<\/strong> even after the<strong> outer function<\/strong> has <strong>completed<\/strong> its <strong>execution<\/strong>.<\/p>\n<p>To get a better understanding of closures, let\u2019s first see how scope works in <strong>nested functions<\/strong>.<\/p>\n<h3>Scope of Variables in Nested Functions<\/h3>\n<p>In Python nested functions, the <strong>enclosed function<\/strong> can <strong>access variables<\/strong> of the <strong>enclosing scope<\/strong>.<\/p>\n<p>Let\u2019s understand this better with an example &#8211;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def outer(name):\n    # this is the enclosing function\n\n    def inner():\n        # this is the enclosed function\n\n        # the inner function accessing the outer function's variable 'name'\n        print(name)\n\n    inner()\n\n# call the enclosing function\nouter('TechVidvan')\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>TechVidvan<\/p>\n<p>Let\u2019s break this code down.<\/p>\n<p>When the <strong>outer function<\/strong> gets <strong>called<\/strong>, the <strong>variable \u2018name\u2019<\/strong> gets the <strong>value \u2018TechVidvan\u2019<\/strong>. The<strong> inner function<\/strong> can <strong>access<\/strong> the <strong>value<\/strong> of this <strong>variable<\/strong>. When the <strong>inner function<\/strong> gets <strong>called<\/strong>, <strong>\u2018Techvidvan\u2019 gets printed<\/strong>. This is how <strong>scope<\/strong> works in <strong>nested functions<\/strong>.<\/p>\n<p>The bottom line is (and it\u2019s worth repeating) &#8211; <strong>\u201cEnclosed functions can access the variables of enclosing functions.\u201d<\/strong><\/p>\n<p>Keeping this in mind, let\u2019s move on to <strong>Python closures<\/strong>.<\/p>\n<h3>Python Closures<\/h3>\n<p>In the example above, we have <strong>called<\/strong> the <strong>inner function inside<\/strong> the <strong>outer function<\/strong>. The <strong>inner function <\/strong>becomes a <strong>closure <\/strong>when we<strong> return <\/strong>the <strong>inner function instead of calling it.<\/strong><\/p>\n<p>So we have a closure in Python if-<\/p>\n<ul>\n<li>We have a nested function, i.e. <strong>function within a function<\/strong><\/li>\n<li>The nested function refers to a <strong>variable<\/strong> of the<strong> outer function<\/strong><\/li>\n<li>The enclosing function <strong>returns<\/strong> the <strong>enclosed function<\/strong><\/li>\n<\/ul>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def outer(name):\n    # this is the enclosing function\n\n    def inner():\n        # this is the enclosed function\n        # the inner function accessing the outer function's variable 'name'\n        print(name)\n\n    return inner\n\n# call the enclosing function\nmyFunction = outer('TechVidvan')\nmyFunction()\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>\u2018TechVidvan\u2019<\/p>\n<p>Here, the <strong>call<\/strong> to <strong>outer function<\/strong> <strong>returns<\/strong> the <strong>inner function<\/strong>. This then gets assigned to<strong> \u2018myFunction\u2019<\/strong>. Now when we <strong>call myFunction<\/strong>, it <strong>prints<\/strong> <strong>\u2018TechVidvan\u2019<\/strong> (which was earlier given as an <strong>argument<\/strong> to <strong>outer<\/strong>).<\/p>\n<p>Do you see what just happened here? Even after<strong> \u2018outer\u2019<\/strong> <strong>finishes<\/strong> its <strong>execution<\/strong> and all its <strong>variables go out of scope<\/strong>, the <strong>value passed<\/strong> to its <strong>argument<\/strong> is still <strong>remembered<\/strong>.<\/p>\n<p>This is the beauty of closures! We can <strong>access<\/strong> the <strong>values<\/strong> of a <strong>function<\/strong> that <strong>no longer exists<\/strong>. You might be thinking that <strong>closure<\/strong> and all seems fine, but why on Earth will I ever use it?<\/p>\n<p>Say no more, pal!<\/p>\n<h3>When and Why do you need to use Closures in Python?<\/h3>\n<p>You can use closures &#8211;<\/p>\n<ul>\n<li><strong>To replace the unnecessary use of class:<\/strong> Suppose you have a class that contains just one method besides the <strong>__init__ method<\/strong>. In such cases, it is often more elegant to use a <strong>closure<\/strong> instead of a <strong>class<\/strong>.<\/li>\n<li><strong>To avoid the use of the global scope:<\/strong> If you have global variables which only<strong> one function<\/strong> in your program will use, think closure. Define the variables in the<strong> outer function<\/strong> and use them in the <strong>inner function<\/strong>.<\/li>\n<li><strong>To implement data hiding:<\/strong> The only way to access the enclosed function is by calling the <strong>enclosing function<\/strong>. There is no way to access the <strong>inner function directly<\/strong>.<\/li>\n<li><strong>To remember a function environment even after it completes its execution:<\/strong> You can then <strong>access<\/strong> the <strong>variables<\/strong> of this environment later in your program.<\/li>\n<\/ul>\n<h3>Wrapping Up!<\/h3>\n<p>Closures are just <strong>functions<\/strong>, but with an <strong>extra<\/strong> environment of <strong>variables<\/strong>. They might seem quite <strong>confusing<\/strong> at first. It will take you a while to <strong>understand<\/strong> them, let alone use them in your program. But once you get a hang of it, you\u2019ll realize how <strong>powerful<\/strong> they are.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you have been into programming for a while, chances are you might\u2019ve heard the word \u2018Closure\u2019 in JavaScript. Turns out, closures are not limited to JavaScript. Python offers support for closures too. In&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79404,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[2989,2990,2991],"class_list":["post-79294","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-advantages-of-python-closures","tag-closures-in-python","tag-python-closures"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Closures in Python with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what are closures in python, why and when to use them, Scope of Variables in Nested Functions and Python closure example for better understanding.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Closures in Python with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what are closures in python, why and when to use them, Scope of Variables in Nested Functions and Python closure example for better understanding.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-07-06T06:00:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Closures in Python with Examples - TechVidvan","description":"Learn what are closures in python, why and when to use them, Scope of Variables in Nested Functions and Python closure example for better understanding.","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:\/\/techvidvan.com\/tutorials\/closures-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Closures in Python with Examples - TechVidvan","og_description":"Learn what are closures in python, why and when to use them, Scope of Variables in Nested Functions and Python closure example for better understanding.","og_url":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-07-06T06:00:39+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Closures in Python with Examples","datePublished":"2020-07-06T06:00:39+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/"},"wordCount":620,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg","keywords":["Advantages of Python closures","Closures in Python","Python Closures"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/","url":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/","name":"Closures in Python with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg","datePublished":"2020-07-06T06:00:39+00:00","description":"Learn what are closures in python, why and when to use them, Scope of Variables in Nested Functions and Python closure example for better understanding.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/closures-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/Closures-in-Python-tv.jpg","width":1200,"height":628,"caption":"Closures in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/closures-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Closures in Python with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=79294"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79294\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79404"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=79294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=79294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=79294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}