Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my code work from interactive shell, but not when run from a file?

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?

like image 847
ben Avatar asked Feb 16 '26 16:02

ben


1 Answers

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

like image 155
DSM Avatar answered Feb 18 '26 06:02

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!