Viktor Mellgren
Viktor Mellgren

Reputation: 4506

classes and methods in python

import unittest
from paycheck import with_checker

class TestStrings(unittest.TestCase):        
    @with_checker([int])
    def test_sort(self, list_of_ints):
        self.assertTrue(isinstance(list_of_ints, list))
        self.assertTrue(len(list_of_ints) == len(qsort(list_of_ints)))
        self.assertTrue(False)


if __name__ == '__main__':
    unittest.main()

    def qsort (list):
        if list == []:
            return []
        else:
            pivot = list [0]
            lesser = qsort([x for x in list[1:] if x<pivot])
            greater = qsort([x for x in list[1:] if x>=pivot])
            return lesser + [pivot] + greater

This gives me global name qsort not defined (even if i have it in the same class). What is the problem here? I suppose it is simple, but I'm not yet very familiar with Python.

Upvotes: 0

Views: 125

Answers (2)

John La Rooy
John La Rooy

Reputation: 304147

The dedent at if __name__... signifies the end of the class definition. You should move those two lines to the bottom, qsort is now part of your class

import unittest
from paycheck import with_checker

class TestStrings(unittest.TestCase):        
    @with_checker([int])
    def test_sort(self, list_of_ints):
        self.assertTrue(isinstance(list_of_ints, list))
        self.assertTrue(len(list_of_ints) == len(qsort(list_of_ints)))
        self.assertTrue(False)

    def qsort (list):
        if list == []:
            return []
        else:
            pivot = list [0]
            lesser = qsort([x for x in list[1:] if x<pivot])
            greater = qsort([x for x in list[1:] if x>=pivot])
            return lesser + [pivot] + greater

if __name__ == '__main__':   # move these two lines
    unittest.main()          # to the bottom

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251373

It looks like you're running the tests before you define the function. Function definitions in Python are executable statements like any other and are executed in the order they're encountered. Since you call unittest.main() before you define qsort, qsort is not defined when the test is run. Move your unittest.main() call after the def qsort block.

While you're at it, it's better not to put the def inside the if __name__=="__main__" block anyway. Usually that if block will be the last bit in your program. Just do

def qsort (list):
    if list == []:
        return []
    else:
        pivot = list [0]
        lesser = qsort([x for x in list[1:] if x<pivot])
        greater = qsort([x for x in list[1:] if x>=pivot])
        return lesser + [pivot] + greater

if __name__ == '__main__':
    unittest.main()

Also note that qsort is not "in the same class" as anything. It's not in any class. It's just a function.

Upvotes: 3

Related Questions