AndrewGrant AndrewGrant - 1 year ago 98
Python Question

"'module' has no attribute" when working with namedtuples

I've run into a bit of a wall here, so I'm going to do my best to explain the issue.

def playGames(jobQueue, ...):
nextJob = jobQueue.get()

def runPool(fens, timesetting, ...):
for fen in fens:
jobQueue.put(Job(gamefen=fen, timecontrol=timesetting))

if __name__ == '__main__':
Job = collections.namedtuple('Job', 'gamefen timecontrol')
playGames(jobQueue, ...) # jobQueue is a multiprocess.Queue() object

After running this, the following error gets thrown.

"'module' object has no attribute 'Job'"

So I moved the Job = collections... line above the if name==main thing and it worked!

But, the way the code is written without the Job = collections... moved will work perfectly fine, on my Ubuntu system.

So Windows7 using python2.7.8 it does not work
Ubuntu14 using python2.7.6 it does work
Ubuntu14 using python3.4.3 it does work

I must be missing something here...


Traceback (most recent call last):
File "c:\Python27\lib\multiprocessing\", line 258, in _bootstrap
File "c:\Python27\lib\multiprocessing\", line 114, in run
self._target(*self._args, **self._kwargs)
File "c:\Users\Andy\Desktop\Github\LucasZinc\", line 338, in play_games
_job = jobQueue.get()
File "c:\Python27\lib\multiprocessing\", line 117, in get
res = self._recv()
AttributeError: 'module' object has no attribute 'Job'

Answer Source

On Windows, the implementation of multiprocessing places additional constraints on code - effectively what happens is a different python interpreter is started for each process, and then these new interpreters load the python code as non-main - so, to use Job, the non-main processes need to have Job defined outside the if __name__=='__main__' conditional statement. See heading below

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download