Correct type-hinting of BindableProperty #3988
Replies: 3 comments 2 replies
-
That's an interesting question, @dantebben! The line status_string: str = binding.BindableProperty() is not correct, because the You could type-annotate it like status_string: binding.BindableProperty = binding.BindableProperty() but this isn't very helpful. As far as I understand, this is what is being inferred automatically, so you can skip the type annotation. By the way, make sure to add a return type for def __init__(self) -> None: The assignment self.status_string = "Initial String" will call the self.status_string: str = "Initial String" But as I just notice, this doesn't cause mypy to complain about type mismatches: self.status_string: str = 42 # no error or self.status_string: str = "Initial String"
self.status_string = 42 # no error I guess we could make status_string = binding.BindableProperty[str]() But right now I don't see a way to make this type optional to avoid breaking existing code. Anyway, I'll convert this question into a feature request. Improving type-annotations for bindable properties would be great. We just have to find out how to do it without a breaking change. |
Beta Was this translation helpful? Give feedback.
-
Hi, @dantebben ! In your case as a possible workaround i would suggest to use a generic typing.Protocol. that for from typing import Callable, TypeVar, Protocol, Optional, Any, NoReturn, Union
T = TypeVar('T')
class BindablePropertyProtocol(Protocol[T]):
def __init__(self, on_change: Optional[Callable[..., Any]] = None) -> None: ...
def __set_name__(self, _: Any, name: str) -> None: ...
def __get__(self, owner: Any, _: Any = None) -> Union[T, NoReturn]: ...
def __set__(self, owner: Any, value: T) -> None: ...
class State:
status_string: BindablePropertyProtocol[str] = binding.BindableProperty()
def __init__(self) -> None:
self.status_string = "Initial String"
self.status_string = 1 # error: Incompatible types in assignment |
Beta Was this translation helpful? Give feedback.
-
Thanks for all of the suggestions. I went with #3988 (comment), and it is working great. I even tried to enter something wrong, and |
Beta Was this translation helpful? Give feedback.
-
Question
I am implementing a class that has several
binding.BindableProperty
properties. I would like to type-hint these, and check the typing using mypy. However, I get errors for each property that has a type hint.Here is a simple example (
example_binding.py
):When I run the example, it works fine. However, running mypy results in:
What is the correct way to type-hint the status_string property, or is there a configuration that needs to be set for mypy for BindableProperty()?
Using:
Python 3.13
mypy 1.13.0
NiceGui 2.5.0
Beta Was this translation helpful? Give feedback.
All reactions