Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting "Cannot access member" error when inside a hasattr check #2237

Closed
kimadeline opened this issue Jan 10, 2022 · 3 comments
Closed

Getting "Cannot access member" error when inside a hasattr check #2237

kimadeline opened this issue Jan 10, 2022 · 3 comments

Comments

@kimadeline
Copy link

Environment data

  • Language Server version: 2022.1.0 (pyright 5829dcbb)
  • OS and version: macOS Big Sur 11.6.1
  • Python version (& distribution if applicable, e.g. Anaconda): Python 3.8 venv

Expected behaviour

When using if hasattr to check if an attribute is present, I shouldn't get a "Cannot access member" error for code inside that condition.

Actual behaviour

I get the following error:

Cannot access member "decorator_list" for type "stmt"
  Member "decorator_list" is unknown (Pylance) reportGeneralTypeIssues

Logs

Copy-pasting the logs froze the window, so I am not going to include them. Let me know if you want them and I'll send them your way 🙂

Code Snippet / Additional information

import ast
import sys

tree = ast.parse("print('Hello World')")

for node in tree.body[1:]:
   line_end = node.lineno - 1
   if hasattr(node, "decorator_list") and sys.version_info.major >= 3:
      line_end -= len(node.decorator_list)
@bschnurr
Copy link
Member

hasattr doesn't inform the correct type. If you want to use static typechecking look at isinstance

   if (isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef) or isinstance(node, ast.ClassDef)) and sys.version_info.major >= 3:
      line_end -= len(node.decorator_list)

@kimadeline
Copy link
Author

isinstance works, thanks! Sadly it can get a bit lengthy. If that's the only option available and having support for hasattr is not possible, feel free to close the issue.

@bschnurr
Copy link
Member

could also try adding a typeguard function

microsoft/pyright#2852 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants