Question

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?

Was it helpful?

Solution

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..]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top