2

I'm new to Python and learning through the O'Reilly "Learning Python" series. I'm stuck on a shelve example and can't figure out why the program doesn't work. I'm trying to build some sample data and then load it into a shelve file. The weird thing is that it works when I type it into the IDLE shell but not when I type it into a .py file and try to run it. Here's my code:

from Python_Learning.person import Person, Manager

bob = Person('Bob Smith', 'dev', 60000)
sue = Person('Sue Jones', job = 'designer', pay = 100000)
tom = Manager('Tom Jones', 1000000)

import shelve
db = shelve.open('persondb')
for object in (bob, sue, tom):
    db[object.name] = object
db.close()

Again, when I run this code on an IDLE shell, I have no problem, but when I run from a .py file I get the following error:

Traceback (most recent call last): File "Documents/Python_Learning/shelve.py", line 7, in import shelve File "Documents/Python_Learning/shelve.py", line 9, in db = shelve.open('persondb') AttributeError: 'module' object has no attribute 'open'

In case it helps, here's the info on the Python version I'm running on Snow Leopard:

Python 3.1.1 (r311:74543, Aug 24 2009, 18:44:04) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin

Thanks for your help to a newbie!

Will

Will Fogel
  • 81
  • 4
  • Could it be that your CLI interpreter is loading a different module? Try `print(shelve.__file__)` in both IDLE and the `.py` file. – Michael Mior Jul 19 '11 at 13:44
  • Note that shelve is powered by pickle, so this isn't a good way to exchange data between instances of the program running on different computers. A malicious user could give you a shelved file that would run malicious code when loaded into your program. The JSON module is better for that sort of thing. – James Jul 19 '11 at 16:34

1 Answers1

7

Rename your module to something else than shelve.py — you're importing yourself.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • Wow, my embarrassment at how simple that answer is is matched only by my gratefulness for you solving a problem that's been holding up my learning all morning. – Will Fogel Jul 19 '11 at 13:48
  • Apparently, I can't mark the question as answered until it's been a few more minutes, but thanks so much for your help! – Will Fogel Jul 19 '11 at 13:49