NameError: name self is not defined Outside Method Scope in Python
Add self as the first argument in method definitions (def my_method(self):) or remove self. in module-level global functions.
Root Cause Analysis
This error occurs when Python executes code referencing the identifier self (such as self.data or self.save()), but the expression is evaluated in a scope where self has not been declared as a local variable or function parameter.
1. Forgetting self in Class Method Signatures
In Python, instance methods do not implicitly receive self. If a method is defined as def calculate(value): return self.base + value, Python parses self as an undeclared global variable, raising NameError: name 'self' is not defined.
2. Using self in Class Body Definition Scope
Code directly inside a class MyClass: block executes during class construction before any instance exists. Writing class Config: default = self.fetch_default() fails because self does not exist during class body execution.
3. Copy-Pasting Method Logic into Global Utility Functions
Refactoring methods into standalone helper functions without removing self. references.
4. Using self Inside Static Methods (@staticmethod)
Static methods decorated with @staticmethod do not receive instance references.
Reproduction Code (MCVE)
# Simulating referencing self outside of an instance method scope
def global_calculator(x, y):
return self.offset + x + y # self is not defined in global function
global_calculator(10, 20)
Solution 1: Declare self as First Parameter in Instance Methods
Include self in the method signature to bind the instance context.
class Calculator:
def __init__(self, offset=5):
self.offset = offset
# Properly declared instance method with self parameter
def calculate(self, x, y):
return self.offset + x + y
calc = Calculator(offset=10)
print(f'Calculation result: {calc.calculate(5, 5)}')
Solution 2: Pass Explicit Parameters in Standalone Functions
If the function is a standalone utility, replace self.attribute with explicit function parameters.
def calculate_total(base_amount, tax_rate=0.20):
return base_amount * (1 + tax_rate)
print(f'Total calculated: ${calculate_total(100.0):.2f}')
A common mistake in beginner Python code is assuming self is a reserved language keyword (like this in Java/C++). In Python, self is merely a conventional variable name passed as the first parameter. You must declare it explicitly in every instance method. Edge cases occur with nested functions inside methods: inner functions do not automatically inherit self unless accessed as a closure. Contrast this error with TypeError: calculate() takes 1 positional argument but 2 were given, which occurs when self is omitted from the method definition and Python auto-injects it.