{"id":31954,"date":"2026-12-01T22:04:26","date_gmt":"2026-12-01T22:04:26","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=31954"},"modified":"2026-12-01T22:04:26","modified_gmt":"2026-12-01T22:04:26","slug":"python-tutorials-namesapce-in-python-with-example","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-tutorials-namesapce-in-python-with-example\/","title":{"rendered":"Python Tutorials: Namesapce in Python with example"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">A namespace in Python maps names to objects. Python has four kinds: built-in, global (module), enclosing and local. Scope decides which of these namespaces Python searches when your code uses a name, following the LEGB rule. This page explains both ideas, fixes the code samples above and shows the <code>global<\/code> and <code>nonlocal<\/code> keywords with runnable examples and their expected output.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Namespace in Python?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves. Each key-value pair maps a name to its corresponding object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Types of Namespace<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"813\" height=\"722\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-1.png\" alt=\"Nested circles showing local namespace inside global namespace inside built-in namespace\" class=\"wp-image-31955\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-1.png 813w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-1-300x266.png 300w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-1-768x682.png 768w\" sizes=\"auto, (max-width: 813px) 100vw, 813px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Scope in Namespace in Python<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"590\" height=\"380\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-2.jpg\" alt=\"Diagram of nested Python scopes: built-in, module global, class and method; lower names override higher ones\" class=\"wp-image-31956\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-2.jpg 590w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-2-300x193.jpg 300w\" sizes=\"auto, (max-width: 590px) 100vw, 590px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Use of Types of Namespaces?<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"936\" height=\"634\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-3.png\" alt=\"Python namespace types: built-in, global, local and enclosing, with when each is created and how long it exists\" class=\"wp-image-31957\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-3.png 936w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-3-300x203.png 300w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-3-768x520.png 768w\" sizes=\"auto, (max-width: 936px) 100vw, 936px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Example Code of Namespace Types <\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"632\" height=\"358\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-4.png\" alt=\"Python code labelling x = 1 as a global variable and x, y in a function and loop as local variables\" class=\"wp-image-31958\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-4.png 632w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-4-300x170.png 300w\" sizes=\"auto, (max-width: 632px) 100vw, 632px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"388\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-5.png\" alt=\"Python discounter closure with variables highlighted as local, enclosing, global and built-in names\" class=\"wp-image-31959\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-5.png 640w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-5-300x182.png 300w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"432\" height=\"435\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-6.png\" alt=\"Python nested functions boxed as global, enclosing and local scopes, with the printed output\" class=\"wp-image-31960\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-6.png 432w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-6-298x300.png 298w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-6-150x150.png 150w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/11\/python-namespace-6-80x80.png 80w\" sizes=\"auto, (max-width: 432px) 100vw, 432px\" \/><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/3fe219a342e69dfb905f616e38b168ea.js\"><\/script>\n\n\n\n<h2 class=\"wp-block-heading\">Video of Namespace of Python<\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\"  id=\"_ytid_38887\"  width=\"760\" height=\"427\"  data-origwidth=\"760\" data-origheight=\"427\" src=\"https:\/\/www.youtube.com\/embed\/HnFA4BASS88?enablejsapi=1&#038;autoplay=0&#038;cc_load_policy=0&#038;cc_lang_pref=&#038;iv_load_policy=1&#038;loop=0&#038;rel=1&#038;fs=1&#038;playsinline=0&#038;autohide=2&#038;theme=dark&#038;color=red&#038;controls=1&#038;disablekb=0&#038;\" class=\"__youtube_prefs__  epyt-is-override  no-lazyload\" title=\"YouTube player\"  allow=\"fullscreen; accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen data-no-lazy=\"1\" data-skipgform_ajax_framebjll=\"\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">The four namespaces and how long they live<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The images above list the namespace types. The table below sets out when each one is created and when it goes away. The lifetime matters because a name only exists while its namespace exists.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Namespace<\/th><th>What it holds<\/th><th>Created<\/th><th>Destroyed<\/th><\/tr><\/thead><tbody><tr><td>Built-in<\/td><td><code>print<\/code>, <code>len<\/code>, <code>range<\/code>, <code>Exception<\/code> and other built-ins<\/td><td>When the interpreter starts<\/td><td>When the interpreter exits<\/td><\/tr><tr><td>Global (module)<\/td><td>Names defined at the top level of a module or script<\/td><td>When the module is imported or the script runs<\/td><td>Usually when the interpreter exits<\/td><\/tr><tr><td>Enclosing<\/td><td>Local names of an outer function, as seen by a nested function<\/td><td>When the outer function is called<\/td><td>When the outer function returns, unless a closure keeps a reference<\/td><\/tr><tr><td>Local<\/td><td>Parameters and names assigned inside a function<\/td><td>When the function is called<\/td><td>When the function returns or raises<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> &quot;Global&quot; in Python means module-level. Each module has its own global namespace, so a variable named <code>config<\/code> in <code>app.py<\/code> and another named <code>config<\/code> in <code>utils.py<\/code> do not clash.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How Python resolves a name: the LEGB rule<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When code reads a name, Python searches the namespaces in a fixed order: <strong>L<\/strong>ocal, then <strong>E<\/strong>nclosing, then <strong>G<\/strong>lobal, then <strong>B<\/strong>uilt-in. It stops at the first match. If no namespace contains the name, it raises <code>NameError<\/code>. The example below defines the same name at three levels so you can see which one wins at each point.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">x = <span class=\"hljs-string\">\"global\"<\/span>\n\ndef outer():\n    x = <span class=\"hljs-string\">\"enclosing\"<\/span>\n\n    def inner():\n        x = <span class=\"hljs-string\">\"local\"<\/span>\n        <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"inner sees:\"<\/span>, x)\n\n    inner()\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"outer sees:\"<\/span>, x)\n\nouter()\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"module sees:\"<\/span>, x)\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"built-in found:\"<\/span>, len)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">inner sees: local\nouter sees: enclosing\n<span class=\"hljs-built_in\">module<\/span> sees: global\nbuilt-<span class=\"hljs-keyword\">in<\/span> found: <span class=\"xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">built-in<\/span> <span class=\"hljs-attr\">function<\/span> <span class=\"hljs-attr\">len<\/span>&gt;<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Each <code>x<\/code> lives in a separate namespace, so assigning one never overwrites another. <code>len<\/code> is not defined anywhere in the file, so the search falls through to the built-in namespace.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Class bodies are not part of the enclosing scope for the methods inside them. A method has to use <code>self.attr<\/code> or <code>ClassName.attr<\/code> to reach class attributes. List, dict and set comprehensions also have their own local scope, so their loop variable does not leak into the surrounding code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Inspecting namespaces in code<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The idea above that a namespace works like a dictionary is literally true for module namespaces. You can look at namespaces at runtime with a few built-ins:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import builtins\n\nx = <span class=\"hljs-number\">10<\/span>\n\ndef show():\n    y = <span class=\"hljs-number\">20<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"locals:\"<\/span>, locals())\n\nshow()\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"x in globals:\"<\/span>, <span class=\"hljs-string\">\"x\"<\/span> in globals())\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"globals()&#91;'x']:\"<\/span>, globals()&#91;<span class=\"hljs-string\">\"x\"<\/span>])\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"len is built-in:\"<\/span>, <span class=\"hljs-string\">\"len\"<\/span> in dir(builtins))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">locals: {<span class=\"hljs-string\">'y'<\/span>: <span class=\"hljs-number\">20<\/span>}\nx in globals: <span class=\"hljs-keyword\">True<\/span>\nglobals()&#91;<span class=\"hljs-string\">'x'<\/span>]: <span class=\"hljs-number\">10<\/span>\nlen is built-in: <span class=\"hljs-keyword\">True<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>globals()<\/code> returns the module&#039;s real namespace dictionary.<\/li>\n\n\n<li><code>locals()<\/code> inside a function returns a snapshot of the local names. Writing to that dictionary does not change the function&#039;s variables.<\/li>\n\n\n<li><code>dir(builtins)<\/code> lists everything in the built-in namespace.<\/li>\n\n\n<li><code>vars(obj)<\/code> returns the <code>__dict__<\/code> of a module, class or instance, which is that object&#039;s attribute namespace.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Changing outer variables with global and nonlocal<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Reading a name from an outer scope needs no keyword. Assigning to it does. Any assignment inside a function makes that name local to the whole function, unless you declare it first. <code>namespace2.py<\/code> above uses <code>global<\/code> to update a module-level variable and prints <code>6<\/code>. To update a variable of an enclosing function, use <code>nonlocal<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def make_counter():\n    count = <span class=\"hljs-number\">0<\/span>\n\n    def increment():\n        nonlocal count   <span class=\"hljs-comment\"># rebind count in make_counter's namespace<\/span>\n        count += <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">return<\/span> count\n\n    <span class=\"hljs-keyword\">return<\/span> increment\n\ncounter = make_counter()\n<span class=\"hljs-keyword\">print<\/span>(counter())  <span class=\"hljs-comment\"># 1<\/span>\n<span class=\"hljs-keyword\">print<\/span>(counter())  <span class=\"hljs-comment\"># 2<\/span>\n<span class=\"hljs-keyword\">print<\/span>(counter())  <span class=\"hljs-comment\"># 3<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>count<\/code> outlives the <code>make_counter()<\/code> call because the returned <code>increment<\/code> function, a closure, keeps a reference to the enclosing namespace. <code>nonlocal<\/code> only searches enclosing function scopes. It never reaches module globals, and Python raises a <code>SyntaxError<\/code> if no enclosing function defines the name.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected versions of the gist examples<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The three gist files above have some problems. <code>namespace1.py<\/code> defines a nested function that is never called and mixes tabs with spaces. A comment in it gets the <code>global<\/code> rule wrong. <code>namespace3.py<\/code> crashes on purpose, but nothing tells the reader that. Here is a runnable version of <code>namespace1.py<\/code> that uses 4-space indentation as PEP 8 recommends:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">var1 = <span class=\"hljs-number\">5<\/span>  <span class=\"hljs-comment\"># global namespace<\/span>\n\ndef some_func():\n    var2 = <span class=\"hljs-number\">6<\/span>  <span class=\"hljs-comment\"># local namespace of some_func<\/span>\n\n    def some_inner_func():\n        var3 = <span class=\"hljs-number\">7<\/span>  <span class=\"hljs-comment\"># local namespace of some_inner_func<\/span>\n        <span class=\"hljs-comment\"># var2 is found in the enclosing scope, var1 in the global scope<\/span>\n        <span class=\"hljs-keyword\">print<\/span>(var1, var2, var3)\n\n    some_inner_func()\n\nsome_func()  <span class=\"hljs-comment\"># prints: 5 6 7<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The comment in <code>namespace1.py<\/code> says that <code>count = count + 1<\/code> uses the global variable without a <code>global<\/code> declaration. That is wrong. Without <code>global count<\/code>, both <code>count = count + 1<\/code> and <code>count = 1<\/code> make <code>count<\/code> local. The first form then fails because it reads the local before giving it a value:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">count = <span class=\"hljs-number\">5<\/span>\n\ndef broken():\n    count = count + <span class=\"hljs-number\">1<\/span>   <span class=\"hljs-comment\"># count is local here, so reading it fails<\/span>\n\nbroken()\n<span class=\"hljs-comment\"># UnboundLocalError: cannot access local variable 'count' where it is not associated with a value<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Older Python versions word this error as <code>local variable &#039;count&#039; referenced before assignment<\/code>. Either way, the fix is <code>global count<\/code>, as <code>namespace2.py<\/code> shows. <code>namespace3.py<\/code> prints two lines and then fails:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">Inside some_func\nInside inner <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span>, <span class=\"hljs-title\">value<\/span> <span class=\"hljs-title\">of<\/span> <span class=\"hljs-title\">var<\/span>: 10\n<span class=\"hljs-title\">Traceback<\/span> (<span class=\"hljs-params\">most recent call last<\/span>):\n  ...\n<span class=\"hljs-title\">NameError<\/span>: <span class=\"hljs-title\">name<\/span> '<span class=\"hljs-title\">var<\/span>' <span class=\"hljs-title\">is<\/span> <span class=\"hljs-title\">not<\/span> <span class=\"hljs-title\">defined<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">An outer function cannot see the locals of an inner function, because the LEGB search only goes outward. If the outer function needs the value, return it:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def some_func():\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Inside some_func\"<\/span>)\n\n    def some_inner_func():\n        <span class=\"hljs-keyword\">var<\/span> = <span class=\"hljs-number\">10<\/span>\n        <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Inside inner function, value of var:\"<\/span>, <span class=\"hljs-keyword\">var<\/span>)\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">var<\/span>\n\n    <span class=\"hljs-keyword\">var<\/span> = some_inner_func()\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Value of var in outer function:\"<\/span>, <span class=\"hljs-keyword\">var<\/span>)\n\nsome_func()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Common namespace errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>UnboundLocalError<\/code> on a variable that exists globally<\/td><td>The function assigns to the name, which makes it local everywhere in that function<\/td><td>Add <code>global name<\/code> or <code>nonlocal name<\/code>, or better, pass the value in and return the result<\/td><\/tr><tr><td><code>NameError: name &#039;x&#039; is not defined<\/code><\/td><td>The name is not in the local, enclosing, global or built-in namespace, often because it was defined in an inner function<\/td><td>Return the value, or define it in a scope that encloses the code that uses it<\/td><\/tr><tr><td><code>TypeError: &#039;list&#039; object is not callable<\/code><\/td><td>A variable named <code>list<\/code> (or <code>str<\/code>, <code>id<\/code>, <code>input<\/code>) hides the built-in<\/td><td>Rename the variable. In an interactive session, <code>del list<\/code> brings the built-in back<\/td><\/tr><tr><td><code>SyntaxError: no binding for nonlocal &#039;x&#039; found<\/code><\/td><td><code>nonlocal<\/code> was used for a name that only exists globally, or does not exist<\/td><td>Use <code>global<\/code> for module variables, or define the name in the enclosing function<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Pass values in as arguments and return results instead of changing globals. Functions are then easier to test and to reason about.<\/li>\n\n\n<li>Keep module-level names for constants (<code>MAX_RETRIES = 3<\/code>) and configuration, and write constants in upper case.<\/li>\n\n\n<li>Do not name variables after built-ins such as <code>list<\/code>, <code>dict<\/code>, <code>id<\/code>, <code>type<\/code> or <code>input<\/code>.<\/li>\n\n\n<li>Use <code>nonlocal<\/code> mainly in closures and decorators that need to keep state. For anything bigger, a class is usually clearer.<\/li>\n\n\n<li>Prefer <code>import module<\/code> over <code>from module import *<\/code>. A wildcard import fills your global namespace with names you cannot see in the code.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between a namespace and a scope in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A namespace is the mapping of names to objects, such as a module&#039;s global names. A scope is the region of code where a namespace can be accessed directly without a prefix. The LEGB rule sets the order in which scopes are searched.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does LEGB stand for in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Local, Enclosing, Global, Built-in. When code uses a name, Python searches these namespaces in that order and uses the first match.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When should I use global versus nonlocal?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>global<\/code> to assign to a module-level variable from inside a function. Use <code>nonlocal<\/code> to assign to a variable of an enclosing function from inside a nested function. Neither keyword is needed if you only read the variable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Are global variables shared between Python modules?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Each module has its own global namespace. To use another module&#039;s variable, import the module and refer to it as <code>module.name<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why do I get UnboundLocalError when the variable exists globally?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Assigning to a name anywhere in a function makes it local to the whole function. Reading it before that assignment therefore fails. Declare it with <code>global<\/code>, or pass the value in as an argument.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/\">TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Top 50 Python Interview Questions and Answers<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>A namespace in Python maps names to objects. Python has four kinds: built-in, global (module), enclosing and local. Scope decides which of these namespaces Python searches when&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[],"class_list":["post-31954","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31954","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=31954"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31954\/revisions"}],"predecessor-version":[{"id":80495,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31954\/revisions\/80495"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=31954"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=31954"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=31954"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}