What’s is Namespaces Local and Global Scope? How to use Namespaces Local and Global Scope in Python!

Hello Everyone, welcome back to DevOpsCheetah.com for  Python Course.
Today you will learn About Namespaces Local and Global Scope and more.

Introduction

A Variable Declared Outside of the function that’s mean we can accessed inside and outside of the function.

I create a variable called ghost and I set it to equal 1. Then I create a function called “game”, and I try to set that variable to 2. Finally, I call my function triggering all the lines of code inside,and now I want you to predict what will this print statement print in the console and what will this print statement print? And it might not be what you expect it to be.

So I would expect that here I’ve got a variable which is equal to one. When this function is called, this variable ghost should now be equal to two. So when it’s printed down here from outside my function, this should be equal to two, and this should also be equal to two.

EXAMPLE:-

ghost = 1

def game():
  ghost = 2
  print(f”Ghost inside the funtion: {ghost}”)

game()
print(f”Ghost Outside the funtion: {ghost}”)

But look at what happens instead.when I run the program. I get Ghost from inside the function equal to 2, but from outside the function, it’s equal to 1.

Output:
Ghost inside the funtion: 2
Ghost Outside the funtion: 1

So what’s going on here? To really understand this we have to understand the concept of scope. And scope is a really, really important thing in programing. You see it in every programming language and although its a little bit different between the programming languages.

So let’s take a look at some other examples before we come back to solve this problem. The first thing to think about is a concept called local scope. Local scope exists within functions.
So for example,
if I was creating a game and I had a function called cocktail which is somehow going to strengthen my player, well, maybe it would have a variable that’s created inside the function. So it could be something like use_num_brand and I could set that to start off where the value of two. Now in this case if I was to go and print this variable use_num_brand from within the function,

def cocktail():
  use_num_brand = 2
  print(use_num_brand)
cocktail()

notice I’m indented here, and of course I need to call this function for that to happen. Notice what happens when I run the code.

Output:
2

It’s equal to two.
That’s what we would expect, right
But notice what happens if I try to print the use_num_brand from outside the function here.

def cocktail():
  use_num_brand = 2
  print(use_num_brand)
cocktail()
print(use_num_brand)

Output:
2

Traceback (most recent call last):
 File “main.py”, line 19, in <module>
    print(use_num_brand)
NameError: name ‘use_num_brand’ is not defined

This firstly gives me an error
This firstly gives me an error right when I’m writing it inside the editor. And when I tried to run it, it gives me an error inside the console. And the error is a name error and it tells me that the name use_num_brand is not defined. Clearly I’ve defined it here,
But why can’t I access it outside the function?
When you create a new variable or indeed a new function inside another function,

SCREEN-SHOT-1

it’s only accessible, you can only use it when you’re inside that function because it has local scope. It’s only valid within the walls of this cocktail function.
What if we wanted it to be accessible outside the function? Well, now we need to think about something called global scope. The only difference between global scope and local scope is where you define or where you create your variables or your functions.
So let’s say we have a different variable.
Let’s say that I created a variable called a Shots and it starts offbeing equal to 4. Now let’s say later on I have the same cocktail function and this use_num_brand of 2.

shots = 4
def cocktail():
  use_num_brand = 2
  print(shots)
cocktail()

So now inside my function cocktail if I wanted to print my shots even though it wasn’t defined within the function, this is perfectly possible. And if I call my function cocktail and the run code as it is,

Output:
4

you will see 4 being printed.
So this has a global scope. It’s available anywhere within our file because it was defined at the top level of the file. and it’s also available outside of functions.

shots = 4
def cocktail():
  use_num_brand = 2
  print(shots)
cocktail()
print(shots)
Output:
4
4

This concept of global and local scope doesn’t just apply to variables. As I alluded to before, it also applies to functions and basically anything else you name. This is a concept called the Namespace.
So we defined this variable “shots”, we define this function “cocktail”

shots = 4
def cocktail():
  use_num_brand = 2
  print(shots)
cocktail()
print(shots)

Anything that you give a name to has a namespace and that namespace is valid in certain scopes. This concept of scope applies to basically anything you name. If I was to nest this function cocktail inside another function,
let’s call it party. Well,

shots = 4
def party():
  def cocktail():
    use_num_brand = 2
    print(shots)
cocktail()
print(shots)

SCREEN-SHOT-2

So whenever you give name to anything, a function or a variable, you have to be aware of where you created it. Now it’s easy to notice where you’ve created functions, we have the def keyword,

def cocktail():

right? But when you create a variable

shots = 4

that’s the first time that you give it a name and you set it equal to something. And where you write that line of code defines the scope of that particular variable. Here it’s outside of every other function, whereas here it’s inside a function actually nested two levels deep.

So it has a local scope to this function.

DOES PYTHON HAVE BLOCK SCOPE

if you’ve come from say C++ or Java there is no such thing as block scope in Python. What this means is that if you were to create an if statement,say

if 4 > 3:
  var = 5

and if you were to create a new variable inside an if block or a while loop or a for loop, basically any sort of block of code that’s indented,

SCREEN-SHOT-3

this does not count as offence. It still has the same scope as its enclosing function, or if there is no enclosing function then it has global scope.
So let me show you a full example. Let’s say we had a list of avengers, so the avengers could be hulk, iron man, or captain america. So now,

avengers = [“Hulk”, “Iron Man”, “Captain America”]

if I was to define a level, right? Like the level that the user is currently playing at, let’s say they’re on level 5.

level = 5
avengers = [“Hulk”, “Iron Man”, “Captain America”]

And I create an if statement and I check if the level is less than level 7

level = 5
avengers = [“Hulk”, “Iron Man”, “Captain America”]
if level < 7:

well, in that case, I want to create a new avengers, but I don’t want the avengers to be too difficult to beat.So I’m going to pick from the list of enemies and I’m going to pick the Second

level = 5
avengers = [“Hulk”, “Iron Man”, “Captain America”]
if level < 7:
  new_avengers = avengers[1]

Notice how,even though this new_avengers is a variable that’s created within this if block, if I go outside the if block

level = 5
avengers = [“Hulk”, “Iron Man”, “Captain America”]
if level < 7:
  new_avengers = avengers[1]
print(new_avengers)

so I’m not indented at all anymore, and I try to print this new avengers,

Output:
Iron Man

this is perfectly valid code. And if I run the code, you’ll see iron man being printed.
But notice how as soon as I embed this within a function,
so let’s define a new function.

level = 5
def create_avengers():
  avengers = [“Hulk”, “Iron Man”, “Captain America”]
  if level < 7:
    new_avengers = avengers[1]
print(new_avengers)

And now this line error is out because within the function there is local scope. So now this new avengers is available anywhere within this function, because blocks like if, while, for, all of these blocks of code with colons and indentation, they don’t count as creating a local scope. So in order to print this new enemy, I actually have to be within the boundary of this function, which means my code has to be here.
The most important thing to remember from this is if you create a variable within a function, then it’s only available within that function. But if you create a variable within an if block or a while loop or a for loop or anything that has the indentation and the colon, then that does not count as creating a separate local scope.

MODIFY A GLOBAL VARIABLE

Lets talk more about the global scope and the concept of modifying something within the global scope. Here we have ghost,

ghost = 1

which is a variable that has global scope,

def myfun():
  ghost = 2
  print(f”Ghost inside the funtion: {ghost}”)

and here we have a function which creates a local scope. Now we think that we’re tapping into this variable and setting it to two. But in fact, we’re actually creating a completely new variable that’s entirely separate from this one. And this is why when we printed it here,

ghost = 1
def myfun():
  ghost = 2
  print(f”Ghost inside the funtion: {ghost}”)

it showed it was equal to 2. But when we printed it here,

myfun()
print(f”Ghost Outside the funtion: {ghost}”

it showed it was actually equal to 1.
If you want to make this a little more obvious, I can call this a zombies and I can set this to be a alien.

ghost = “zombies”
def myfun():
  ghost = “alien”
  print(f”Ghost inside the funtion: {ghost}”)
myfun()
print(f”Ghost Outside the funtion: {ghost}”)

And when I hit run, you can see again, this prints alien, this prints zombies,

Output:
Ghost inside the funtion: alien
Ghost Outside the funtion: zombies

because these two variables are actually entirely different things. And we’re not changing this right here at all, we’re just creating a new variable that has a local scope. Now it’s usually a terrible idea to call your local variables and your global variables the same name. But in this case, what we actually wanted to do was we wanted to modify this variable, we wanted to do something like,

ghost = 1
def myfun():
  ghost += 1
  print(f”Zombies inside the funtion: {ghost}”)
myfun()
print(f”Zombies Outside the funtion: {ghost}”)

maybe += 1. And notice how as soon as I write += 1, hat my editor starts going crazy and tells me that this local variable ghost is defined in an enclosing scope is referenced before assignment.

SCREEN-SHOT – 4

What does that mean? It means that the editor thinks you’re trying to tap into a local variable that you defined somewhere around here.

ghost = 1
def myfun():
  ghost = 0
  ghost += 1
  print(f”Zombies inside the funtion: {ghost}”)
myfun()
print(f”Zombies Outside the funtion: {ghost}”)

And then you tried to modify it by adding one to the previous value, but you actually haven’t defined it. What we wanted to do though, is we wanted to tap into this variable and change it here. In order to do this,we actually have to explicitly say that we have a global variable

ghost = 1
def myfun():
  global ghost
  ghost += 1
  print(f”Zombies inside the funtion: {ghost}”)
myfun()
print(f”Zombies Outside the funtion: {ghost}”)

which is called ghost that’s defined somewhere outside of this function. And that is the zombies that we want to use inside this function. So it basically takes that global ghost into the function and allows you to modify it. Without this line of code

global ghost

we cannot modify something that is global within a local scope.Now there’s a reason why it’s so difficult to modify something that has global scope. You probably don’t actually want to do this very often, because it’s confusing and it’s prone to creating bugs and errors. Because this variable with global scope

ghost = 1

could have been created anywhere in your code, right? And you would be modifying it completely independent of when you created it. So it might’ve been days between when you wrote this code and when you wrote this code and it just makes everything more fallible, more easy to fail This is why very often people will tell you when they’re teaching you Python to avoid modifying global scope. You can read it, that’s not a problem. You can use it within your code, like we are here.

ghost = 1
def myfun():
  print(f”Zombies inside the funtion: {ghost}”)
myfun()
print(f”Zombies Outside the funtion: {ghost}”)

Output:
Zombies inside the funtion: 1
Zombies Outside the funtion: 1

But don’t try to modify it within a function that has local scope. But what can you do instead? What if you wanted to have this functionality like a function that changes the number of ghost? How can you achieve this without modifying the global scope within the function? Well, you could use what we learned about return statements instead, right? What if instead of modifying the ghost, you actually just simply returned it as the output.

ghost = 1
def myfun():
  print(f”Zombies inside the funtion: {ghost}”)
  return ghost + 1
myfun()
print(f”Zombies Outside the funtion: {ghost}”)

So return the current value of ghost + 1. Now once you call this function, you’ll get hold of the output and you can save it to the global variable ghost.

ghost = 1
def myfun():
  print(f”Zombies inside the funtion: {ghost}”)
  return ghost + 1
global = myfun()
print(f”Zombies Outside the funtion: {ghost}”)

So this now means that this function can be taken away and placed anywhere in your code and you don’t actually need to know how it works. As long as you know that this is how you increase enemies, then all you have to do is just call it.

PYTHON CONSTANTS & GLOBAL SCOPE

Remember, you should be careful with variables that have global scope, but don’t believe the people who tell you that you should never use global scope. Global scope can be incredibly useful especially when you’re defining constants. Global constants are variables which you define and you’re never planning on changing it ever again. It’s just something like,

EXAMPLE:

pi = 3.14

you want to look it up once and you want to put it into your code and you never want to look it up ever again. And every other time you want to use it, say inside of a function, then all you want to do is just tap into that value of pi.

pi = 3.14
def calc():
  pi

So usually, in order to differentiate these constants which you’re pretty much never going to change from the variables which you are likely to change, he naming convention in Python is to turn it into all uppercase. if you had PI or you had a URL that you needed to use, or you have some sort of Twitter acount, then these are all going to be uppercased, separated with underscores.

PI = 3.14
URL = “https://www.devopscheetah.com/”
TWITTER_ACOUNT = “@CheetahDevops”

What this means is that later on in your function and you want to use one of these global constants, as soon as you type it,

SCREEN SHOT -5

you can see it’s the uppercase and you know to remind yourself to not modify this inside your code.Now that we’ve talked a little bit about scope, it’s time to put your knowledge into action.

So, Today You will learned What’s is Namespaces Local and Global Scope? How to use Namespaces Local and Global Scope in Python !

Thank you ❤️

Check out “What is Dictionary” and How to use Dict{} in python!

Leave a Reply

Your email address will not be published. Required fields are marked *