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

Dynamic property not supported #153

Closed
walkinrain2008 opened this issue Jun 20, 2019 · 2 comments
Closed

Dynamic property not supported #153

walkinrain2008 opened this issue Jun 20, 2019 · 2 comments

Comments

@walkinrain2008
Copy link

Dynamic property not supported

class PP():
    pass
a=PP()
a.arg = "1"
print(a,a.arg)

Problems:

Cannot access member 'arg' on type 'PP'

Code is right!

@erictraut
Copy link
Collaborator

This is by design. Any static type checker needs to make certain assumptions to be effective. If pyright assumed that any property could be added dynamically to any class, its value would drop significantly because it wouldn't be able to report a wide variety of common bugs.

If you want to dynamically add properties to your classes, you have a few choices:

  1. Don't use a static type checker.
  2. Define a __setattr__ magic method for the class, which tells pyright that the class was designed for use with dynamic attributes. This will effectively disable most type checking for that class, so it should be used very sparingly if you're serious about static type checking.
  3. Don't dynamically add properties. Declare all class and instance variables in your class.

If you want to get the most value out of static type checking, option #3 is my recommendation.

@Timmmm
Copy link

Timmmm commented Apr 17, 2023

For anyone else, here's the code that worked for me (I only read the attributes; presumably if you set them you also need __setattr__).

    if TYPE_CHECKING:
        def __getattribute__(self, name: str) -> Any:
            ...

Might be nice to document this.

(And yeah don't do this unless you are forced to work with people that don't get static types.)

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

3 participants