1

I have a class that uses its attributes as a dictionary. Like this:

class Foo:

  def set(self, name: str, value: int):
    setattr(self, name, value)

  def get(self, name: str) -> Optional[int]:
    return getattr(self, name, None)

Is there any way to write down a type annotation to indicate that all member variables are int (if present)? Ideally in a way that Pyright understands.

1 Answer 1

1

This syntax appears to partially work:

class Foo:
  __dict__: dict[str, int]

  def set(self, name: str, value: int):
    setattr(self, name, value)

  def get(self, name: str) -> Optional[int]:
    return getattr(self, name, None)

It is valid syntax, and it does mean Pyright treats self.__dict__ as the correct type. Unfortunately it's not quite smart enough to change the return type of getattr() which still returns Any, but it's better than nothing!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.