Search code examples
pythondictionarypool

NameError: name 'f' is not defined when using pool.map(f, range()) in class


I'm new to python and I'm trying to load the CPU using pool.map(). The following code does the loading on the CPU when it is not included in a class

def f(x):
    while True:
        x*x

def load(cores):
    print('utilizing %d cores' % (cores/2))
    pool = Pool(10)
    pool.map(f, range(6))

However, when I put it in a class and try to run the code

class test_cpu:

    def f(x):
        while True:
            x*x

    def load(cores):
        print('utilizing %d cores' % (cores/2))
        pool = Pool(10)
        pool.map(f, range(6))

if __name__ == '__main__':
    print('There are %d CPUs in your PC' % multiprocessing.cpu_count())
    cores_count = multiprocessing.cpu_count()
    input_user = input('What do you want to tes? type CPU, Memory or Both: ')
    input_user.lower()
    if input_user == 'cpu':
        test_cpu.load(cores_count)


when I type CPU it prints this error, stating that the function f is not defined

utilizing 4 cores
Traceback (most recent call last):
  File "test_all.txt", line 81, in <module>
    test_cpu.load(cores_count)
  File "test_all.txt", line 45, in load
    pool.map(f, range(6))
NameError: name 'f' is not defined

what should I do to fix this?


Solution

  • You are treating the methods as static class methods. Here are two ways to fix your code:

    1. using @staticmethod. Less preferred method, uses class methods (not object-oriented):
    class test_cpu:
        @staticmethod  # changed
        def f(x):
            while True:
                x * x
    
        @staticmethod  # changed
        def load(cores):
            print("utilizing %d cores" % (cores / 2))
            pool = Pool(10)
            pool.map(test_cpu.f, range(6))  # changed
    
    1. adding self and creating a test_cpu instance:
    import multiprocessing
    from multiprocessing import Pool
    
    
    class test_cpu:
        def f(self, x):  # changed
            while True:
                x * x
    
        def load(self, cores):  # changed
            print("utilizing %d cores" % (cores / 2))
            pool = Pool(10)
            pool.map(self.f, range(6))  # changed
    
    
    if __name__ == "__main__":
        print("There are %d CPUs in your PC" % multiprocessing.cpu_count())
        cores_count = multiprocessing.cpu_count()
        input_user = input("What do you want to tes? type CPU, Memory or Both: ")
        input_user.lower()
        test_cpu_instance = test_cpu()  # changed
        if input_user == "cpu":
            test_cpu_instance.load(cores_count)  # changed