python className not defined NameError

user2058724 picture user2058724 · Mar 10, 2014 · Viewed 19.9k times · Source

I have a class which i need to instantiate in order to call a method that it contains. When I access it from another class it works fine but when i run from terminal it says :

File "myClass.py", line 5, in <module>
  class MyClass:
File "myClass.py", line 23, in ToDict
  td=MyClass()
NameError: name 'MyClass' is not defined

Pasting the code:

class MyClass:
    def convert(self, fl):
        xpD = {}
        # process some stuff
        return xpD

    if __name__ == "__main__":
        source = sys.argv[1]
        td = MyClass()
        needed_stuff = td.convert(source)
        print(needed_stuff)

Answer

Blckknght picture Blckknght · Mar 10, 2014

The problem is that your if __name__ == "__main__" block is inside of your class definition. This will cause an error, as the code within the if will be run as part of the class being created, before the class been bound to a name.

Here's a simpler example of this error:

class Foo(object):
    foo = Foo() # raises NameError because the name Foo isn't bound yet

If you format your code like this (that is, with the if unindented at the top level), it should work correctly:

class MyClass:
    def convert(self, fl):
        xpD = {}
        # process some stuff
        return xpD

if __name__ == "__main__":
    source = sys.argv[1]
    td = MyClass()
    needed_stuff = td.convert(source)
    print(needed_stuff)