site logo

Learn to Python. Build the Future.


Category: (All)
❮  Go Back

07. Understanding Python Scope and Modules: Variables, Namespaces & Code Organization

Introduction

In Python, managing where variables live (scope) and how you organize code into reusable files (modules) are vital concepts. Scope determines which parts of your program can access a name (variable, function), while modules let you group related functionality into separate files. Together, these help you write clean, maintainable Python projects.


Python Scope

What Is Scope?

Scope refers to the region of a program where a variable or name is visible or can be accessed. If you declare a name in one scope, it might not be available in another.


Local Scope

When you define a variable inside a function, it belongs to that function’s local scope. You can use it only within that function.

def myfunc():
x = 300
print(x)

myfunc()
# print(x) here would cause an error (x isn’t defined globally)

If you have nested functions, inner functions can access names from their enclosing (outer) function’s scope.


def outer():
x = 300
def inner():
print(x)
inner()

outer()


Global Scope

Variables defined outside any function are in the global scope. They can be accessed from any function (unless masked by a local variable).


x = 300

def myfunc():
print(x)

myfunc()
print(x)


Using the global Keyword

If you want to modify a global variable inside a function, you must declare it as global.


x = 300

def myfunc():
global x
x = 200

myfunc()
print(x) # now prints 200


The nonlocal Keyword

In nested functions, if you want to assign to a variable in an enclosing scope (not global), use nonlocal. This lets you modify a variable defined in the outer function from an inner function.


Python Modules


What Is a Module?

A module is a file containing Python definitions and statements (functions, classes, variables) that you can import and reuse in other code. Think of it as a code library.

([turn0search1])


Creating a Module

To create a module, put your functions or classes in a .py file. For example, in mymodule.py:


def greeting(name):
print("Hello, " + name)

Then in another file, you can import and use it:


import mymodule
mymodule.greeting("Jonathan")


Variables and Objects in Modules

Modules can contain variables, dictionaries, lists, or classes in addition to functions. You access them via module_name.variable_name.

([turn0search1])


Import Variations

  1. Import with alias:

import mymodule as mm
mm.greeting("Alice")
  1. Import specific names:

from mymodule import greeting
greeting("Bob")
  1. List module contents:
  2. Use the built-in dir() function to list names defined in a module.

import platform
print(dir(platform))


Built-in Modules

Python comes with many built-in modules you can import (e.g. math, os, random). You do not need to install them.

([turn0search5])


Modules Execution Behavior

When you import a module, the Python interpreter executes all its top-level code once. That means functions, class definitions, and other statements at the top level run during import.

Also, modules have their own global namespace—variables inside are separate from your script’s globals unless explicitly referenced.

You can also write a module so it can act as both importable module and executable script using:

if __name__ == "__main__":
# code to run when file is executed directly


Module Search Path

When you import a module, Python searches a list of directories (including your script’s directory, built-in modules, and installed modules).

You can also reload a module (in interactive environments) using importlib.reload().

([turn0search15])


Summary

  1. Scope determines where names are accessible: local (inside functions), global (module-level), and the special cases of global and nonlocal.
  2. Modules let you break your program into reusable pieces. You define functions, variables, and classes inside .py files and import them in other scripts.
  3. Together, proper use of scope and modules helps you write organized, clear, and maintainable Python code.


07. Understanding Python Scope and Modules Variables Namespaces Code Organization

coldshadow44 on 2025-10-11



(0)





Showing comments related to this post.




Member's Sites: