The Python Oracle

NameError: name 'self' is not defined

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Nameerror: Name 'Self' Is Not Defined
00:19 Accepted Answer Score 205
00:54 Answer 2 Score 20
01:09 Answer 3 Score 16
01:50 Thank you

--

Full question
https://stackoverflow.com/questions/1802...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #nameerror

#avk47



ACCEPTED ANSWER

Score 206


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.




ANSWER 2

Score 20


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



ANSWER 3

Score 17


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