Typing is not correct for bracket-notation access for a Dataset variable #8046
-
Hi, This is my first message here. I landed here following the "❓ Usage question" section in the Issue creation interface. Indeed, this is more a question than an issue. QuestionI noticed that type hinting in VSCode is not working for bracket-notation access for a Dataset variable. xarray version: Reproducible exampleThe following code-snippet is self contained. However, for type hinting, VSCode would be required. I assume any type-hinting mechanism would have the same issue. import xarray as xr
ds = xr.Dataset({'da': xr.DataArray()})
# Dot notation
dot_notation = ds.da # Type hinting (in VSCode): `(type alias) dot_notation: Any`
# Bracket notation
bracket_notation = ds["da"] # Type hinting (in VSCode): `(variable) bracket_notation: DataArray` As you can see the type is widened to "Any", while "DataArray" would be the correct answer. Is it even possible to enforce type hinting on dot access notation? Indeed, we can dot-access other attributes of a DataArray, such as its methods, while bracket notation ( I looked into the code for the See Line 1506 in 92c8b33 So, does the xarray community recommends to favor bracket notation over dot notation to enforce type hinting in projects, and favor dot notation for shorter feedback loops (debugging, jupyter notebooks) where static typing is less important than type speed? Thanks a lot! PS: Regarding I have done a search for similar discussions, I looked for |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi, welcome! 👋 If I understand your question correctly, you want to know why the return type of the dot notation is In [1]: import xarray as xr
In [2]: da = xr.DataArray(0, attrs={'t' : 'calendar'})
In [3]: da.t
Out[3]: 'calendar'
Exactly. At least that's what I do personally. |
Beta Was this translation helpful? Give feedback.
-
Hello, Thanks for your reply. What I did is replace the dot notations in my code by bracket notations to improve the typing coverage. da.x = something # won't work
da["x"] = something # works So overall it seems the bracket notation is more "robust"! |
Beta Was this translation helpful? Give feedback.
Hi, welcome! 👋
If I understand your question correctly, you want to know why the return type of the dot notation is
Any
. The answer is because the dot notation can also be used to access theattributes
dictionary on xarray objects, which can store arbitary metadata. For example in this case the return type is a string:E…