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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type annotations for progress #4688

Merged
merged 6 commits into from
May 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 25 additions & 14 deletions lib/streamlit/elements/progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import cast
from typing import cast, TYPE_CHECKING, Union
from typing_extensions import TypeAlias

import streamlit
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Progress_pb2 import Progress as ProgressProto

if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator


# Currently, equates to just float, but we can't use `numbers.Real` due to
# https://github.com/python/mypy/issues/3186
FloatOrInt: TypeAlias = Union[int, float]


class ProgressMixin:
def progress(self, value):
def progress(self, value: FloatOrInt) -> "DeltaGenerator":
"""Display a progress bar.

Parameters
Expand All @@ -46,29 +54,32 @@ def progress(self, value):
# TODO: standardize numerical type checking across st.* functions.
progress_proto = ProgressProto()

if isinstance(value, float):
if 0.0 <= value <= 1.0:
progress_proto.value = int(value * 100)
if isinstance(value, int):
if 0 <= value <= 100:
progress_proto.value = value
else:
raise StreamlitAPIException(
"Progress Value has invalid value [0.0, 1.0]: %f" % value
"Progress Value has invalid value [0, 100]: %d" % value
)

elif isinstance(value, int):
if 0 <= value <= 100:
progress_proto.value = value
elif isinstance(value, float):
if 0.0 <= value <= 1.0:
progress_proto.value = int(value * 100)
else:
raise StreamlitAPIException(
"Progress Value has invalid value [0, 100]: %d" % value
"Progress Value has invalid value [0.0, 1.0]: %f" % value
)
else:
raise StreamlitAPIException(
"Progress Value has invalid type: %s" % type(value).__name__
)

return self.dg._enqueue("progress", progress_proto)
return cast(
"DeltaGenerator",
self.dg._enqueue("progress", progress_proto),
)

@property
def dg(self) -> "streamlit.delta_generator.DeltaGenerator":
def dg(self) -> "DeltaGenerator":
"""Get our DeltaGenerator."""
return cast("streamlit.delta_generator.DeltaGenerator", self)
return cast("DeltaGenerator", self)