Forums

PicklingError Attribute Lookup Failed

I've tried several different actions to resolve the error and posted on Stack Overflow but can't seem to figure out what's causing this error. Does anyone know what is causing the error and what would need to be changed/moved around to resolve? Error and code found below (from PythonAnywhere).

' Traceback (most recent call last): File "/home/tarnette/assessment7question1a.py", line 79, in <module> main() File "/home/tarnette/assessment7question1a.py", line 14, in main dictionaryNations() File "/home/tarnette/assessment7question1a.py", line 31, in dictionaryNations pickle.dump(nationDictionary, outfile) _pickle.PicklingError: Can't pickle <class 'main.Nation'>: attribute lookup Nation on main failed

import pickle

infile = open("/home/tarnette/UN/UN.txt", 'r')

def main(): dictionaryNations()

def dictionaryNations(): nationDictionary = {}

for line in infile:
    data = line.split(',')

    country = Nation()
    country.setCountryName(data[0])
    country.setContinent(data[1])
    country.setPopulation(float(data[2]))
    country.setArea(float(data[3]))

    nationDictionary[country.getCountryName()] = country

outfile = open("nationsDict.dat", 'wb')
pickle.dump(nationDictionary, outfile)
outfile.close()

return nationDictionary

class Nation: def init(self): self._countryName = "" self._continent = "" self._population = 0.0 self._area = 0.0

def setCountryName(self, countryName):
    self._countryName = countryName

def getCountryName(self):
    return self._countryName

def setContinent(self, continent):
    self._continent = continent

def getContinent(self):
    return self._continent

def setPopulation(self, population):
    self._population = population

def getPopulation(self):
    return self._population

def setArea(self, area):
    self._area = area

def getArea(self):
    return self._area

def popDensity(self):
    return self._population / self._area

main()`

The problem is that you're trying to pickle an object from the module where it's defined. If you move the Nation class into a separate file and import it into your script, then it should work.

Brilliant, I took your advice, imported the file and got the program to work. Thank you!