How to read file during module import?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 12 14:09:05 EDT 2010


En Fri, 09 Apr 2010 19:16:14 -0300, Jeremy <jlconlin at gmail.com> escribió:
> On Apr 9, 4:02 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
>> En Fri, 09 Apr 2010 18:04:59 -0300, Jeremy <jlcon... at gmail.com>  
>> escribió:
>>
>> > A related question: Can I parse the data once and keep it somewhere
>> > instead of reading the supporting file every time?  I tried pickling
>> > but that wouldn't work because I have custom classes.  (Either that or
>> > I just don't know how to pickle—this is a highly probable event.)
>>
>> What kind of "custom classes"?
>
> My custom classes are not very fancy.  They basically are dictionaries
> and lists organizing the data in the supporting file.  I was actually
> surprised they didn't pickle because the classes were so simple.
>
>> # pickle some_object
>> with open(filename, "wb") as f:
>>    pickle.dump(some_object, f, -1)
>
> When I did this I got the following error:
>
> PicklingError: Can't pickle <class '__main__.element'>: it's not found
> as __main__.element
>
> Am I just being dumb?

No, but maybe you're redefining 'element':

py> from pickle import dumps
py> class Foo(object):
...   pass
...
py> x = Foo()
py> class Foo(object):
...   pass
...
py> dumps(x)
Traceback (most recent call last):
...
pickle.PicklingError: Can't pickle <class '__main__.Foo'>: it's not the  
same obj
ect as __main__.Foo

Using reload() may lead to this error too. Basically, the class says: "I  
am 'DonQuijote', from module 'LaMancha'". But nobody at LaMancha knows  
DonQuijote, or they say DonQuijote is a different person.

-- 
Gabriel Genellina




More information about the Python-list mailing list