Python Forum

Full Version: AttributeError class object has no attribute list object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am calling an API to retrieve different types of information in multiple calls. I use an authorization process to gain access to the API and then a 'main_menu' to select API endpoints to retrieve data. The authorization and main menu functions are written in a separate module from the functions used to make the endpoint calls. The first call in the first function returns dates information, and then the second call in a second function uses the list values returned in the first function. These two endpoint functions are written in a class of their own and on a separate module. In the first function I am able to successfully produce three different lists (year, month, day). However, I am running into an AttributeError in the second function on a line that intends to call the list. Ultimately, I would like to use the list values(defined in the first function) in the payload of the second function to make multiple calls using different sets of date values.

#first module

def oauth()

def main_menu(session, base_url):
    """
    Provides the different options for the sample application: Market Quotes, Account List

    :param session: authenticated session
    """


    menu_items = {"1": "Market Quotes",
                  "2": "Account List/Order",
                  "3": "MSFT Quote",
                  "4": "GOOG Quote",
                  "5": "MSFT Option Expiry Dates",
                  "6": "GOOG Option Expiry Dates",
                  "7": "MSFT Option Chain",
                  "8": "GOOG Option Chain",
                  "10": "Exit"}

    while True:
        print("")
        options = menu_items.keys()
        for entry in options:
            print(entry + ")\t" + menu_items[entry])
        selection = input("Please select an option: ")
        if selection == "1":
            market = Market(session, base_url)
            market.quotes()
        elif selection == "2":
            accounts = Accounts(session, base_url)
            accounts.account_list()
        elif selection == "3":
            market = Market1(session, base_url)
            market.quotes()
        elif selection == "4":
            market = Market2(session, base_url)
            market.quotes()
        elif selection == "5":
            market = Market3(session, base_url)
            market.quotes()
        elif selection == "6":
            market = Market4(session, base_url)
            market.quotes()
        elif selection == "7":
            market = Market5(session, base_url)
            market.quotes0()
            market.quotes()
        elif selection == "8":
            market = Market6(session, base_url)
            market.quotes()
        elif selection == "10":
            break
        else:
            print("Unknown Option Selected!")


if __name__ == "__main__":
    oauth()
the above is written in the first module, I am trying to call selection 7 "MSFT Option Chain"

    def quotes0(self):
        """
        Calls quotes API to provide quote details for equities, options, and mutual funds

        :param self: Passes authenticated session in parameter

#lines here seem to be working fine

return year_dates
return month_dates
return day_dates

    def quotes(self):
        """
        Calls quotes API to provide quote details for equities, options, and mutual funds

        :param self: Passes authenticated session in parameter
        """

        # URL for the API endpoint
        url = self.base_url + "/v1/market/optionchains.json"

        for i in range(len(self.year_dates)):

            payload = {"symbol": "MSFT", "chainType": "CALLPUT", "includeWeekly": "true", "expiryYear": self.year_dates[i], "expiryMonth": self.month_dates[i], "expiryDay": self.day_dates[i], "strikePriceNear": "233", "noOfStrikes": "20"}

            # Make API call for GET request
            response = self.session.get(url, params=payload)
            logger.debug("Request Header: %s", response.request.headers)

            if response is not None and response.status_code == 200:

                # Handle and parse response
                print("")
                data = response.json()

                if data is not None and "OptionChainResponse" in data and "OptionPair" in data["OptionChainResponse"]:
                    for option in data["OptionChainResponse"]["OptionPair"]:
                        print(option["Call"]["optionType"])
                        print(option["Call"]["openInterest"])
                        print(option["Call"]["volume"])

                else:
                    # Handle errors
                    if data is not None and 'QuoteResponse' in data and 'Messages' in data["QuoteResponse"] \
                            and 'Message' in data["QuoteResponse"]["Messages"] \
                            and data["QuoteResponse"]["Messages"]["Message"] is not None:
                        for error_message in data["QuoteResponse"]["Messages"]["Message"]:
                            print("Error: " + error_message["description"])
                    else:
                        print("Error: Quote API service error")

            else:
                logger.debug("Response Body: %s", response)
                print("Error: Quote API service error")
the above is the stored in a second module

The error in the console is reading

Error:
Traceback (most recent call last): File "C:/Users/scttb/PycharmProjects/pythonProject1/EtradePythonClient/etrade_python_client/etrade_python_client.py", line 146, in <module> oauth() File "C:/Users/scttb/PycharmProjects/pythonProject1/EtradePythonClient/etrade_python_client/etrade_python_client.py", line 80, in oauth main_menu(session, base_url) File "C:/Users/scttb/PycharmProjects/pythonProject1/EtradePythonClient/etrade_python_client/etrade_python_client.py", line 129, in main_menu market.quotes() File "C:\Users\scttb\PycharmProjects\pythonProject1\EtradePythonClient\etrade_python_client\market\Market5.py", line 106, in quotes for i in range(len(self.year_dates)): AttributeError: 'Market5' object has no attribute 'year_dates'
Again, my goal is to be able to print values in the def quotes() for each set of date values generated in def quotes0()

Any help would be appreciated! Confused
first listing line 49 looks like an error:
market.quotes0()
That's the problem with error messages. They only tell you where the program crashes, not necessarily where the error is. The crash is caused by Markets not having an attribute named "year_dates". The error may be that some other problem is leading to Markets not executing code that leads to creating the "year_dates" attribute.

I find this interesting
#lines here seem to be working fine
 
return year_dates
return month_dates
return day_dates
If those are not commented out I would expect a syntax error. If they do run they point to year_dates not being an attribute of some class that I don't get to see very much of.
daenhystad, read post 2
first listing line 49 looks like an error:
market.quotes0()
Since the error trace shows an error in "quotes()" I assume the error message is not from the posted code. There is some debugging being done and we are seeing code from one debugging session and an error from another. Renaming quotes() to quotes0() is not going to generate the reported error.
I've found a work around to the problem. Instead of approaching the goal with a using multiple modules and a class object I reorganized my pycharm files directory and am calling the API with multiple functions in the same module.

def oauth()
 quotes0(session, base_url)
def quotes0(session, base_url)
quotes(year_dates, month_dates, day_dates)
def quotes(session, base_url, year_dates, month_dates, day_dates)
print(print_var)

oauth()
This approach seems to allow me to combine returned values from multiple functions for use in the last function.