3

I am trying to use the pprint module to check out some vars in Python, which I can happily do using the interactive shell and the code below:

import pprint
pp = pprint.PrettyPrinter()
stuff = ['cakes','bread','mead']
pp.pprint(stuff)

However, when I put the above into pprint.py and run it using python pprint.py I get the error:

$ python dev/pars/pprint.py 
Traceback (most recent call last):
  File "dev/pars/pprint.py", line 1, in ?
    import pprint
  File "/home/origina2/dev/pars/pprint.py", line 2, in ?
    pp = pprint.PrettyPrinter()
AttributeError: 'module' object has no attribute 'PrettyPrinter'

What is different about the way modules are called when running Python code from a file compared to the interactive shell?

ben
  • 1,583
  • 2
  • 11
  • 12

1 Answers1

10

You named your program pprint.py, so at the line import pprint it tries to import itself. It succeeds, but your pprint.py doesn't contain anything called PrettyPrinter.

Change your code's name. [And, to be clear, delete any pprint.pyc or pprint.pyo files..]

DSM
  • 342,061
  • 65
  • 592
  • 494
  • i copied your code exactly into a file called `test.py` and it runs with no problem. Do you have issues with other python modules? Maybe a reinstall would help? – kaveman Mar 11 '12 at 22:46
  • Ok, try copying it into pprint.py, running it, then renaming the file and running it again :) – ben Mar 11 '12 at 22:51