0

I get the error: "AttributeError: 'function' object has no attribute 'request_symbol'" when running my code. Can somebody explain how can i define new parameter in def and then later use it?

def request_income_statement (symbol, api_key):
    url = 'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=' + symbol + '&apikey=' + api_key
    r = requests.get(url)
    data_IS = r.json()
    request_symbol = data_IS.get('symbol')
    return request_symbol

request_income_statement(symbol, api_key)

print(request_symbol)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
mptrsn217
  • 13
  • 3
  • `result = request_income_statement(symbol, api_key)` and then `print result`. – luk2302 Jul 07 '22 at 09:59
  • 3
    Your code should not raise that error though? Are you sure your sample code is representative of the code that caused the error? This code should raise a `NameError`, not an `AttributeError` (which would be fixed by changing `request_income_statement(symbol, api_key)` to `request_symbol = request_income_statement(symbol, api_key)`) – Amadan Jul 07 '22 at 10:00
  • Note to self: revisit this closure after coming to a decision about the canonical to use for questions of this type. – Karl Knechtel Jul 07 '22 at 10:07

2 Answers2

1

You are correctly returning a value from your function, with the last line return request_symbol

But perhaps your confusion is that only the value is returned, not the variable, i.e. the name request_symbol does not exist outside the function.

When you call the function request_income_statement(symbol, api_key) ....that statement itself returns a value (the value returned from your function), but you are currently not assigning the value to any var name.

Try this:

def request_income_statement (symbol, api_key):
    url = 'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=' + symbol + '&apikey=' + api_key
    r = requests.get(url)
    data_IS = r.json()
    request_symbol = data_IS.get('symbol')
    return request_symbol

myvar = request_income_statement(symbol, api_key)

print(myvar)

Do you see how the value moves between different var names now?

Of course you could also re-use the request_symbol name like:

request_symbol = request_income_statement(symbol, api_key)

print(request_symbol)

But it's important to note that the name request_symbol outside of your function is a different variable from the one inside the function.

Anentropic
  • 32,188
  • 12
  • 99
  • 147
0

I would say, that you need to assign the request_symbol to a variable outside of your function.

try something like:

result = request_income_statement(symbol, api_key)
print(result)

instead of your last two lines