VSCode python snippet:
import yfinance as yf
from datetime import date
end_date = date.today() # <--- The color of today is yellow. Right click on
# today and then click on "Go to Definition", it works.
data = yf.download(ticker, start=start_date, end=end_date)
print(data.head()) # <--- The color of head is white. Right click on head
# and then click on "Go to Definition", it does NOT work.
average_yield = data['Close'].mean() # <--- The color of mean is white. Right
# click on mean and then click on "Go to
# Definition", it does NOT work.
OS: Windows
language server is set to Pylance
yfinance has been pip installed probably because clicking on yf.download and then "Go to Definition" works.
When try to go to the definition of both head() and mean(), the error message is "No definition found for head or mean".
Why it works for today() method of date but not for head() and mean()?
2
Answers
From the inspiration of Denel, I add the following code right after yf.download.
data = pd.DataFrame(data)
This effectively convert data from Any to DataFrame. As you can see, both head() and mean() methods change to yellow color.
I think this happens because
yf.download()
does not return a type and thus it cannot be determined beforehand what functions can be called on thedata
variable and which ones they would refer to.This is also why VSCode does not autocomplete function names when you start writing
data.
For example, here we know that we have a string, we can already determine beforehand (either because we manually defined it to be a string or because the return type of the function is a string) which functions can be used on the variable. This allows VSCode to suggest functions that can be used on strings.
However, because
data
is defined to be of typeany
(because that is the return type of theyf.download()
function), VSCode cannot determine beforehand what kind of functions can work on this variable, because only during execution we will know whatdata
is.VSCode cannot suggest a function that can be used on this variable, and it would also not know to which function the
head()
ormean()
point, because those names are probably used in a lot of libraries.