Author tim.peters
Recipients Bharatsolanki, eric.smith, tim.peters
Date 2020-03-18.20:55:38
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1584564938.32.0.139491584701.issue40005@roundup.psfhosted.org>
In-reply-to
Content
u1 is a global _only_ in a process that runs `function()`, which declares u1 global and assigns it a value.  You have no sane expectation that a worker process (none of which run `function()`) will know anything about it.

Are you sure you're running 2.7 and 3.7 on the same machine?  It's impossible that this code ever "worked" under Windows, but it might under Linux-y systems, which use `fork()` to create worker processes.

The traceback you showed was obviously run under Windows.  Under Python 2.7.11 on Windows, I get the same kind of error:

NameError: global name 'u1' is not defined

This is the code:

from multiprocessing import Pool
import traceback

class Utils:
    def __init__(self):
       self.count = 10

def function():
    global u1
    u1 = Utils()
    l1 = range(3)
    process_pool = Pool(1)
    try:
        process_pool.map(add, l1, 1)
        process_pool.close()
        process_pool.join()
    except Exception as e:
        process_pool.terminate()
        process_pool.join()
        print(traceback.format_exc())
        print(e)

def add(num):
     total = num + u1.count
     print(total)

if __name__ == "__main__":
    function()
History
Date User Action Args
2020-03-18 20:55:38tim.peterssetrecipients: + tim.peters, eric.smith, Bharatsolanki
2020-03-18 20:55:38tim.peterssetmessageid: <1584564938.32.0.139491584701.issue40005@roundup.psfhosted.org>
2020-03-18 20:55:38tim.peterslinkissue40005 messages
2020-03-18 20:55:38tim.peterscreate