Python NameError: name is not defined

Question:

I have a python script and I am receiving the following error:

Traceback (most recent call last):
  File "C:UsersTimDesktoppop-erptest.py", line 1, in <module>  
  s = Something()
  NameError: name 'Something' is not defined

Here is the code that causes the problem:

s = Something()
s.out()

class Something:
    def out():
        print("it works")

This is being run with Python 3.3.0 under Windows 7 x86-64.

Why can’t the Something class be found?

Asked By: user1899679

||

Answers:

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

Answered By: user574435

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Answered By: Blender

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That’s because the class has not been defined yet at this point.
The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right
Answered By: Tomasz Bartkowiak
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.