{"id":74322,"date":"2019-12-18T15:07:40","date_gmt":"2019-12-18T09:37:40","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=74322"},"modified":"2024-08-22T17:58:41","modified_gmt":"2024-08-22T12:28:41","slug":"python-namespace-and-scope","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/","title":{"rendered":"Python Namespace and scope &#8211; Get unique names for each object"},"content":{"rendered":"<p>In your school, college or office, confusion can arise because of people having the same names. This confusion is usually resolved by providing a <strong>unique identity<\/strong> like using first name and last name. The same problem can arise in programming also.<\/p>\n<p>If you write a few lines of code then it is not a problem to assign unique names to every variable. But when you load <strong>external modules<\/strong> and write thousands of lines of code then it is not possible to use unique and meaningful names for every object or variable.<\/p>\n<p>This is why namespaces are important and this article will be covering everything about Python namespace and scope.<\/p>\n<h3>What is Python Namespace?<\/h3>\n<p>A namespace is a <strong>collection of names<\/strong>. Python implements namespaces as <strong>dictionaries<\/strong>. Imagine it as a name-to-object mapping where names are the keys and objects are the values.<\/p>\n<p>A namespace allows us to have <strong>unique<\/strong> names for each object. If you don\u2019t know, this is just a quick reminder to tell you that <strong>strings<\/strong>, <strong>lists<\/strong>, <strong>functions<\/strong>, etc. everything in Python is an object.<\/p>\n<p>In simple words, we can say that the role of a namespace is like a <strong>surname<\/strong>.<\/p>\n<p>There can be multiple <strong>\u201cTom\u201d<\/strong> in the same class but there will be a single <strong>\u201cTom Hanks\u201d<\/strong> (let\u2019s just assume this) in the class and with surname, you can identify between multiple<strong> \u201cTom\u201d<\/strong>.<\/p>\n<p>The Python interpreter does the same thing to understand what exact method or variable one is pointing to in the <strong>code<\/strong>. The namespace word itself can be broken down as <strong>name (which is a unique identifier) + space (which means relating to scope)<\/strong>.<\/p>\n<p>The name can be anything from <strong>method name<\/strong> to <strong>variable name<\/strong> and <strong>space<\/strong> depends upon the location from where we are trying to <strong>access<\/strong> a <strong>variable<\/strong> or a <strong>method<\/strong>.<\/p>\n<h3>Types of Namespaces in Python<a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/types-of-namespace-in-python.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-74572 aligncenter\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/types-of-namespace-in-python.jpg\" alt=\"Python namespace types\" width=\"500\" height=\"432\" \/><\/a><\/h3>\n<p>Namespaces are of basically three types:<\/p>\n<h4>1. Built-in Namespace<\/h4>\n<p>This namespace includes <strong>functions<\/strong> and <strong>exception names<\/strong> that are built-in in the Python. Examples include built-in functions like print(), len(), and built-in exceptions like ValueError and TypeError. The built-in namespace is always available and can be accessed from anywhere in the code, providing a foundation of readily available utilities.<\/p>\n<h4>2. Global Namespace<\/h4>\n<p>This namespace includes <strong>names<\/strong> from the modules that are <strong>imported<\/strong> in the project. It is created when we include the <strong>module<\/strong> and it lasts until the <strong>script ends<\/strong>. Variables and functions defined at the top level of a script or module are part of the global namespace. This allows them to be accessed from any part of the code after their declaration, as long as the script or module is still running.<\/p>\n<h4>3. Local Namespace<\/h4>\n<p>The local names inside a function come under a local namespace. This namespace is created when the function is called and its scope ends when the function returns a value or exits. Variables defined within a function are local to that function and cannot be accessed from outside. This encapsulation helps prevent conflicts between variables in different parts of the program and allows for better modularity and readability.<\/p>\n<h3>Python Scope<\/h3>\n<p>With namespaces, we can uniquely <strong>identify<\/strong> all the names inside a program. However, it doesn\u2019t mean that we can use the variable names anywhere we want. It also has some <strong>scope<\/strong> that indicates the part of the program where we can access them.<\/p>\n<p>We can directly access the variables without any <strong>prefix<\/strong> when they are in the namespace. The lifetime of a namespace is dependent on the scope of objects. When the scope of an object comes to end, the lifetime of the namespace also comes to an <strong>end<\/strong>.<\/p>\n<p>So, we cannot access the inner namespace scope\u2019s objects from an <strong>outer namespace<\/strong>.<\/p>\n<p><strong>Python has the following scopes &#8211;<\/strong><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/types-of-scope-in-python.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-74680 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/types-of-scope-in-python.jpg\" alt=\"python scope types\" width=\"600\" height=\"462\" \/><\/a><\/p>\n<p>When a name is <strong>referenced<\/strong> in Python, the interpreter searches the name in the <strong>namespace<\/strong> starting from the <strong>smallest scope<\/strong> in the diagram and gradually moves towards the outermost scope.<\/p>\n<ul>\n<li>The local scope, which is the innermost scope contains a list of local names that are only available in the function.<\/li>\n<li>Enclosing scopes are seen in nested functions where names are searched in the nearest outside function.<\/li>\n<li>The global scope is the module-level scope. When we import modules, they get added to the global scope.<\/li>\n<li>The outermost scope is of the built-in names scope. The interpreter searches names in this scope at last.<\/li>\n<\/ul>\n<h3>Example of Python Namespaces and Scope<\/h3>\n<p>Now, we will see some examples of namespaces and scope &#8211;<\/p>\n<p><strong>Example 1<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">#var1 is in the global namespace\r\nvar1 = 5\r\ndef function():\r\n\r\n    # var2 is in the local namespace\r\n    var2 = 6\r\n    def inner_function():\r\n\r\n        # var3 is in the nested local\r\n        # namespace\r\n        var3 = 7<\/pre>\n<p>In this example, the <strong>var1<\/strong> is declared in the <strong>global namespace<\/strong> because it is not <strong>enclosed<\/strong> inside any function. So it is accessible everywhere in the script.<\/p>\n<p><strong>var2<\/strong> is inside the function(). So, it can be accessed only inside the function() and outside the function, it no longer exists.<\/p>\n<p><strong>var3<\/strong> also has a local scope, the function is nested and we can use var3 only inside <strong>inner_function()<\/strong>.<\/p>\n<p><strong>Example 2<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">var = \"10\"\r\ndef example():\r\n  var = \"30\"\r\n  def method():\r\n    global var\r\n    var = \"40\"\r\n    def function():\r\n      global var\r\n      var = \"50\"\r\n      print(\"Function Scope: \" + var)\r\n    function()\r\n    print(\"Method Scope: \" + var)\r\n  method()\r\n  print(\"Example Scope: \" + var)\r\nexample()\r\nprint(\"Module Scope: \" + var)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Function Scope: 50<br \/>\nMethod Scope: 50<br \/>\nExample Scope: 30<br \/>\nModule Scope: 50<\/div>\n<p>Let\u2019s break down how we got the following output &#8211;<\/p>\n<p>In the global scope first, we declared the<strong> variable \u2018var\u2019<\/strong> and initialized it with <strong>value = 10<\/strong>.<\/p>\n<p>In the example() function, we declare a <strong>local variable \u2018var\u2019 =30<\/strong>.<\/p>\n<p>Since they are declared in <strong>different namespaces<\/strong>, we can have variables with the <strong>same names<\/strong> in <strong>different scopes<\/strong>.<\/p>\n<p>The global keyword is used to indicate that we are referencing the <strong>global variable<\/strong> in this scope that is why in <strong>function()<\/strong> the value now holds <strong>50<\/strong>.<\/p>\n<p>Same as<strong> method() function<\/strong> and the<strong> example() function<\/strong> is holding the <strong>local variable<\/strong> whose value is <strong>30<\/strong> and in the end, the last value of the <strong>global variable<\/strong> was<strong> 50<\/strong>.<\/p>\n<h3>Summary<\/h3>\n<p>In this python namespace and scope article of TechVidvan, we studied about the namespaces and scope in Python. They are necessary to solve the problem of <strong>conflicting names<\/strong> while naming objects.<\/p>\n<p>We saw the different types of <strong>namespaces<\/strong> (built-in, global and local) and scopes. Further on, we saw easy examples of namespaces and scope.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In your school, college or office, confusion can arise because of people having the same names. This confusion is usually resolved by providing a unique identity like using first name and last name. The&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":74616,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1102,1103,1104,1105,1106,1107,1108,1109],"class_list":["post-74322","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-global-namespace","tag-local-namespace","tag-namespace-and-scope-in-python","tag-python-namespace-and-scope","tag-python-namespace-example","tag-python-namespace","tag-python-scope","tag-python-scope-example"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Namespace and scope - Get unique names for each object - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python namespace and scope - Get to know about what is namespace in Python, its types, and the scope of Python with examples.\" \/>\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\/python-namespace-and-scope\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Namespace and scope - Get unique names for each object - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python namespace and scope - Get to know about what is namespace in Python, its types, and the scope of Python with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/\" \/>\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=\"2019-12-18T09:37:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-22T12:28:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\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=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Namespace and scope - Get unique names for each object - TechVidvan","description":"Python namespace and scope - Get to know about what is namespace in Python, its types, and the scope of Python with examples.","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\/python-namespace-and-scope\/","og_locale":"en_US","og_type":"article","og_title":"Python Namespace and scope - Get unique names for each object - TechVidvan","og_description":"Python namespace and scope - Get to know about what is namespace in Python, its types, and the scope of Python with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2019-12-18T09:37:40+00:00","article_modified_time":"2024-08-22T12:28:41+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.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":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Namespace and scope &#8211; Get unique names for each object","datePublished":"2019-12-18T09:37:40+00:00","dateModified":"2024-08-22T12:28:41+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/"},"wordCount":989,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.jpg","keywords":["Global Namespace","Local Namespace","namespace and scope in python","python namespace and scope","python Namespace example","python namespace()","Python scope","Python scope example"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/","url":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/","name":"Python Namespace and scope - Get unique names for each object - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.jpg","datePublished":"2019-12-18T09:37:40+00:00","dateModified":"2024-08-22T12:28:41+00:00","description":"Python namespace and scope - Get to know about what is namespace in Python, its types, and the scope of Python with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-namespace-and-scope-1.jpg","width":802,"height":420,"caption":"python namespace and scope"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-namespace-and-scope\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Namespace and scope &#8211; Get unique names for each object"}]},{"@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\/74322","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=74322"}],"version-history":[{"count":2,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74322\/revisions"}],"predecessor-version":[{"id":447674,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74322\/revisions\/447674"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/74616"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=74322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=74322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=74322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}