0

This is part of a script that produces documentation from YAML files. It doesn't get very far.

    for yaml_filename in yaml_files:
        with open(yaml_filename, 'r') as yaml_file:
            try:
                yaml_contents = yaml.safe_load(yaml_file)
                for api_name in yaml_contents:
                    api = yaml_contents[api_name]
                    if 'api_doc' in api.keys(): # <---- error generated here
                        format_api(api_name, api, html_file)
                    else:
                        # Handle the generation of HTML documentation for APIs
                        # that have not been updated to include the api_doc
                        # object.

The initial error I'm getting is this:

AttributeError: 'str' object has no attribute 'keys'

My initial interpretation was that, if api is missing the keys attribute, then I can correct the if test to handle that, and still get to the else branch and correctly parse the file. So my attempted fix looks like this:

                    if hasattr(api,keys) and 'api_doc' in api.keys():

But now the error message generated is:

NameError: name 'keys' is not defined

I thought that the hasattr() test would just return false but it's throwing an error. I'm at the limit of my understanding of python objects here, and I don't know how to search for what I don't know. What is going on? Was the script okay all along? Is the problem that yaml.safe_load() failed? Or is api badly formatted somehow?

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
  • second argument of `hasattr` should be a string, like so: `if hasattr(api, 'keys')` – oskros Jun 17 '21 at 13:24
  • Yes, @oskros, this is essentially a duplicate. I might not have spotted the quotes, though, and I do appreciate everyone's patience in pointing out my error. – Tim Randall Jun 17 '21 at 13:33

1 Answers1

2

You have to specify the attribute name as a string, not an identifier:

if hasattr(api, "keys") and ...:
chepner
  • 497,756
  • 71
  • 530
  • 681