Search code examples
pythonpprint

Why do I get an error "AttributeError: module 'pprint' has no attribute 'PrettyPrinter'


I'm trying to print out the values in my yaml file using pprint and I run into this error despite installing pprint and importing and everything

    #!/bin/python

    import yaml
    import subprocess
    import os
    import pprint

    pp = pprint.PrettyPrinter(indent=4)



    #pre-requisite-run the script in an empty directory

    #read data from the config yaml file
    def read_yaml(file):
        with open(file, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                # print(config)
            except yaml.YAMLError as exc:
                print(exc)
                print("\n")
        return config

    d = read_yaml("config.yaml")

    #print out contents of the yaml file with a better structure
    pp.pprint(d)

Error message when I run in the command line:

    Traceback (most recent call last):
      File "pprint.py", line 6, in <module>
        import pprint
      File "../pprint.py", line 8, in <module>
        pp = pprint.PrettyPrinter(indent=4)
    AttributeError: module 'pprint' has no attribute 'PrettyPrinter'

Solution

  • Your file is named pprint.py thus overshadowing the pprint module that you want to use. Rename your file to something different.