NameError: name 'self' is not defined

Question:

Why such structure

class A:
    def __init__(self, a):
        self.a = a

    def p(self, b=self.a):
        print b

gives an error NameError: name 'self' is not defined?

Asked By: chriss

||

Answers:

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It’s a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Update 2022: Python developers are now considering late-bound argument defaults for future Python versions.

Answered By: intgr

For cases where you also wish to have the option of setting ‘b’ to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b
Answered By: Andrew

A self NameError can also occur if you fail to define self inside a method signature. This error typically will appear as TypeError, as there will be a mismatch between expected and given arguments[1]. However, if you accept a variable number of arguments, self will be arg[0], and the variable self will be undefined.

A minimal example.

class Obj:
    def foo(*args):
        print(self.bar)

>NameError: name ‘self’ is not defined

Correction:

class Obj:
    def baz(self, *args):
        print(self.bar)

[1] http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

Answered By: Erich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.