Access a variable outside of a function in python

Global Variables

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

Let's see an example of how a global variable is created in Python.

Example 1: Create a Global Variable

x = "global"

def foo():
    print("x inside:", x)


foo()
print("x outside:", x)

Output

x inside: global
x outside: global

In the above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change the value of x inside a function?

x = "global"

def foo():
    x = x * 2
    print(x)

foo()

Output

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work, we use the global keyword. Visit Python Global Keyword to learn more.


Local Variables

A variable declared inside the function's body or in the local scope is known as a local variable.

Example 2: Accessing local variable outside the scope

def foo():
    y = "local"


foo()
print(y)

Output

NameError: name 'y' is not defined

The output shows an error because we are trying to access a local variable y in a global scope whereas the local variable only works inside foo() or local scope.


Let's see an example on how a local variable is created in Python.

Example 3: Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

def foo():
    y = "local"
    print(y)

foo()

Output

local

Let's take a look at the earlier problem where x was a global variable and we wanted to modify x inside foo().


Global and local variables

Here, we will show how to use global variables and local variables in the same code.

Example 4: Using Global and Local variables in the same code

x = "global "

def foo():
    global x
    y = "local"
    x = x * 2
    print(x)
    print(y)

foo()

Output

global global 
local

In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.

After calling the foo(), the value of x becomes global global because we used the x * 2 to print two times global. After that, we print the value of local variable y i.e local.


Example 5: Global variable and Local variable with same name

x = 5

def foo():
    x = 10
    print("local x:", x)


foo()
print("global x:", x)

Output

local x: 10
global x: 5

In the above code, we used the same name x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().

When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the variable.

Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the global scope of the variable.


Nonlocal Variables

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

Let's see an example of how a nonlocal variable is used in Python.

We use nonlocal keywords to create nonlocal variables.

Example 6: Create a nonlocal variable

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)


outer()

Output

inner: nonlocal
outer: nonlocal

In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().

Note : If we change the value of a nonlocal variable, the changes appear in the local variable.

If you want to avoid global, one possible approach is to define a class. Each class instance has its own attributes; there is also a class attribute space where instances can share an attribute between them.

Object-oriented programming can be challenging to get into if you are new to Python, but this might actually be a good time to start playing with it.

class Thing:
    shared = "foo"

    def __init__(self):
        """
        This gets called when you create a new Thing()
        """
        self.bar = "baz"  # default value for new instances

    def get_bar(self):
        return self.bar

    def set_bar(self, value):
        self.bar = value

Now, let's create two instances.

first = Thing()
second = Thing()

The get_bar and set_bar methods are not strictly necessary in simple examples like this one. You can also do

second.bar = "ick"
print(second.bar)
# "ick"
print(first.bar)
# "baz"

(though for more complex scenarios, you probably want to require users to call the setter and getter methods; there are ways to force this - see e.g. What's the pythonic way to use getters and setters?)

If you change a class attribute via one instance, it will not be changed in the other instances, either.

second.shared = "poo"
print(first.shared)
# "foo"

But if you change it in the class itself, it will be changed in all the instances which have not separately overridden the shared value.

Thing.shared = "zoom"
print(first.shared)
# "zoom"
print(second.shared)
# "poo", still

To recap, you create a new Thing instance by calling Thing(); this will run the __init__ method before returning the new instance. Inside the class, the instance is the first argument to every (non-static, non-class) method, and conventionally called self (though you could get away with calling it shirley if you wanted to, as far as the Python interpreter is concerned).

There's a lot more to classes; the main selling point is probably that you can create subclasses which inherit from their parent class but can override some behaviors (common examples often involve real-world concepts like animals or vehicles, but a class can just be anything where you want to create a type and encapsulate its behavior, and perhaps override some methods in derived types).

How do you access a variable from the outside of a function?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.

How do you access a variable in a function Python?

Using the return statement to get variable from function in Python. The return statement in Python is used to return some value from a function in Python. Since we cannot access the variable defined within the function from the outside, we can return it using the return statement to get variable from function in Python ...

Can you use a variable outside of an IF statement Python?

No, variables declared inside an if statement would not be accessible directly outside an if statement because if statements have their own scope.

Which Python keyword allows access to a function variable outside of the function where the variable was declared?

In Python, global keyword allows you to modify the variable outside of the current scope.