Python typing_extensions.Final() Examples
The following are 25
code examples of typing_extensions.Final().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing_extensions
, or try the search function
.

Example #1
Source File: test_core.py From dataclasses-jsonschema with MIT License | 6 votes |
def test_final_field(): @dataclass class TestWithFinal(JsonSchemaMixin): """Dataclass with final field""" name: Final[str] expected_schema = { 'type': 'object', 'description': 'Dataclass with final field', 'properties': { 'name': {'type': 'string'} }, 'required': ['name'] } assert TestWithFinal.json_schema() == compose_schema(expected_schema) assert TestWithFinal.from_dict({'name': 'foo'}) == TestWithFinal(name='foo') assert TestWithFinal(name='foo').to_dict() == {'name': 'foo'}
Example #2
Source File: cloudpickle.py From ray with Apache License 2.0 | 6 votes |
def _is_parametrized_type_hint(obj): # This is very cheap but might generate false positives. # general typing Constructs is_typing = getattr(obj, '__origin__', None) is not None # typing_extensions.Literal is_litteral = getattr(obj, '__values__', None) is not None # typing_extensions.Final is_final = getattr(obj, '__type__', None) is not None # typing.Union/Tuple for old Python 3.5 is_union = getattr(obj, '__union_params__', None) is not None is_tuple = getattr(obj, '__tuple_params__', None) is not None is_callable = ( getattr(obj, '__result__', None) is not None and getattr(obj, '__args__', None) is not None ) return any((is_typing, is_litteral, is_final, is_union, is_tuple, is_callable))
Example #3
Source File: __init__.py From python_withings_api with MIT License | 6 votes |
def sleep_get( self, startdate: Optional[DateType] = None, enddate: Optional[DateType] = None, data_fields: Optional[Iterable[GetSleepField]] = None, ) -> SleepGetResponse: """Get sleep data.""" params: Final[ParamsType] = {} update_params( params, "startdate", startdate, lambda val: arrow.get(val).timestamp ) update_params(params, "enddate", enddate, lambda val: arrow.get(val).timestamp) update_params( params, "data_fields", data_fields, lambda fields: ",".join([field.value for field in fields]), ) update_params(params, "action", "get") return new_sleep_get_response( self.request(path=self.PATH_V2_SLEEP, params=params) )
Example #4
Source File: __init__.py From python_withings_api with MIT License | 6 votes |
def notify_get( self, callbackurl: str, appli: Optional[NotifyAppli] = None ) -> NotifyGetResponse: """ Get subscription. Return the last notification service that a user was subscribed to, and its expiry date. """ params: Final[ParamsType] = {} update_params(params, "callbackurl", callbackurl) update_params(params, "appli", appli, lambda appli: appli.value) update_params(params, "action", "get") return new_notify_get_response( self.request(path=self.PATH_NOTIFY, params=params) )
Example #5
Source File: __init__.py From python_withings_api with MIT License | 6 votes |
def notify_revoke( self, callbackurl: Optional[str] = None, appli: Optional[NotifyAppli] = None ) -> None: """ Revoke a subscription. This service disables the notification between the API and the specified applications for the user. """ params: Final[ParamsType] = {} update_params(params, "callbackurl", callbackurl) update_params(params, "appli", appli, lambda appli: appli.value) update_params(params, "action", "revoke") self.request(path=self.PATH_NOTIFY, params=params)
Example #6
Source File: common.py From python_withings_api with MIT License | 6 votes |
def response_body_or_raise(data: Any) -> Dict[str, Any]: """Parse withings response or raise exception.""" parsed_response: Final = dict_or_raise(data) status_any: Final = parsed_response.get("status") status: Final = int_or_none(status_any) if status is None: raise UnknownStatusException(status=status) if status in STATUS_SUCCESS: return cast(Dict[str, Any], parsed_response.get("body")) if status in STATUS_AUTH_FAILED: raise AuthFailedException(status=status) if status in STATUS_INVALID_PARAMS: raise InvalidParamsException(status=status) if status in STATUS_UNAUTHORIZED: raise UnauthorizedException(status=status) if status in STATUS_ERROR_OCCURRED: raise ErrorOccurredException(status=status) if status in STATUS_TIMEOUT: raise TimeoutException(status=status) if status in STATUS_BAD_STATE: raise BadStateException(status=status) if status in STATUS_TOO_MANY_REQUESTS: raise TooManyRequestsException(status=status) raise UnknownStatusException(status=status)
Example #7
Source File: __init__.py From python_withings_api with MIT License | 6 votes |
def notify_update( self, callbackurl: str, appli: NotifyAppli, new_callbackurl: str, new_appli: Optional[NotifyAppli] = None, comment: Optional[str] = None, ) -> None: """Update the callbackurl and or appli of a created notification.""" params: Final[ParamsType] = {} update_params(params, "callbackurl", callbackurl) update_params(params, "appli", appli, lambda appli: appli.value) update_params(params, "new_callbackurl", new_callbackurl) update_params(params, "new_appli", new_appli, lambda new_appli: new_appli.value) update_params(params, "comment", comment) update_params(params, "action", "update") self.request(path=self.PATH_NOTIFY, params=params)
Example #8
Source File: __init__.py From python_withings_api with MIT License | 6 votes |
def __init__( self, client_id: str, consumer_secret: str, callback_uri: str, scope: Iterable[AuthScope] = tuple(), mode: Optional[str] = None, ): """Initialize new object.""" self._client_id: Final = client_id self._consumer_secret: Final = consumer_secret self._callback_uri: Final = callback_uri self._scope: Final = scope self._mode: Final = mode self._session: Final = OAuth2Session( self._client_id, redirect_uri=self._callback_uri, scope=",".join((scope.value for scope in self._scope)), )
Example #9
Source File: common.py From python_withings_api with MIT License | 6 votes |
def get_measure_value( from_source: Union[ MeasureGetMeasGroup, MeasureGetMeasResponse, Tuple[MeasureGetMeasGroup, ...] ], with_measure_type: Union[MeasureType, Tuple[MeasureType, ...]], with_group_attrib: Union[ MeasureGetMeasGroupAttrib, Tuple[MeasureGetMeasGroupAttrib, ...] ] = MeasureGroupAttribs.ANY, ) -> Optional[float]: """Get the first value of a measure that meet the query requirements.""" groups: Final = query_measure_groups( from_source, with_measure_type, with_group_attrib ) return next( iter( tuple( float(measure.value * pow(10, measure.unit)) for group in groups for measure in group.measures ) ), None, )
Example #10
Source File: common.py From python_withings_api with MIT License | 6 votes |
def _flexible_tuple_of( items: Iterable[Any], fun: Callable[[Any], GenericType] ) -> Tuple[GenericType, ...]: """Create a tuple of objects resolved through lambda. If the lambda throws an exception, the resulting item will be ignored. """ new_items: Final[List[GenericType]] = [] for item in items: try: new_items.append(fun(item)) except Exception: # pylint:disable=broad-except print( "Warning: Failed to convert object. See exception for details.", traceback.format_exc(), ) return tuple(new_items)
Example #11
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def __init__( self, credentials: Credentials, refresh_cb: Optional[Callable[[Credentials], None]] = None, ): """Initialize new object.""" self._credentials = credentials self._refresh_cb: Final = refresh_cb token: Final = { "access_token": credentials.access_token, "refresh_token": credentials.refresh_token, "token_type": credentials.token_type, "expires_in": str(int(credentials.token_expiry) - arrow.utcnow().timestamp), } self._client: Final = OAuth2Session( credentials.client_id, token=token, client=WebApplicationClient( # nosec credentials.client_id, token=token, default_token_placement="query" ), auto_refresh_url="%s/%s" % (WithingsAuth.URL, WithingsAuth.PATH_TOKEN), auto_refresh_kwargs={ "client_id": credentials.client_id, "client_secret": credentials.consumer_secret, }, token_updater=self._update_token, )
Example #12
Source File: test_common.py From python_withings_api with MIT License | 5 votes |
def test_get_measure_value() -> None: """Test function.""" response: Final = MeasureGetMeasResponse( offset=0, more=False, timezone=TIMEZONE0, updatetime=arrow.get(100000), measuregrps=( MeasureGetMeasGroup( attrib=MeasureGetMeasGroupAttrib.MANUAL_USER_DURING_ACCOUNT_CREATION, category=MeasureGetMeasGroupCategory.USER_OBJECTIVES, created=arrow.utcnow(), date=arrow.utcnow(), deviceid="dev1", grpid=1, measures=( MeasureGetMeasMeasure(type=MeasureType.WEIGHT, unit=1, value=10), MeasureGetMeasMeasure( type=MeasureType.BONE_MASS, unit=-2, value=20 ), ), ), ), ) assert get_measure_value(response, MeasureType.BODY_TEMPERATURE) is None assert get_measure_value(response.measuregrps, MeasureType.BODY_TEMPERATURE) is None assert ( get_measure_value(response.measuregrps[0], MeasureType.BODY_TEMPERATURE) is None ) assert get_measure_value(response, MeasureType.WEIGHT) == 100 assert get_measure_value(response.measuregrps, MeasureType.WEIGHT) == 100 assert get_measure_value(response.measuregrps[0], MeasureType.WEIGHT) == 100 assert get_measure_value(response, MeasureType.BONE_MASS) == 0.2 assert get_measure_value(response.measuregrps, MeasureType.BONE_MASS) == 0.2 assert get_measure_value(response.measuregrps[0], MeasureType.BONE_MASS) == 0.2
Example #13
Source File: test_init.py From python_withings_api with MIT License | 5 votes |
def withings_api_instance() -> WithingsApi: """Test function.""" client_id: Final = "my_client_id" consumer_secret: Final = "my_consumer_secret" credentials: Final = Credentials( access_token="my_access_token", token_expiry=arrow.utcnow().timestamp + 10000, token_type="Bearer", refresh_token="my_refresh_token", userid=_USERID, client_id=client_id, consumer_secret=consumer_secret, ) return WithingsApi(credentials)
Example #14
Source File: common.py From python_withings_api with MIT License | 5 votes |
def new_measure_get_meas_response(data: dict) -> MeasureGetMeasResponse: """Create GetMeasResponse from json.""" timezone: Final = timezone_or_raise(data.get("timezone")) return MeasureGetMeasResponse( measuregrps=_flexible_tuple_of( data.get("measuregrps", ()), lambda group: new_measure_get_meas_group(group, timezone), ), more=data.get("more"), offset=data.get("offset"), timezone=timezone, updatetime=arrow_or_raise(data.get("updatetime")).to(timezone), )
Example #15
Source File: common.py From python_withings_api with MIT License | 5 votes |
def new_get_sleep_summary_serie(data: dict) -> GetSleepSummarySerie: """Create GetSleepSummarySerie from json.""" timezone: Final = timezone_or_raise(data.get("timezone")) return GetSleepSummarySerie( date=arrow_or_raise(data.get("date")).to(timezone), enddate=arrow_or_raise(data.get("enddate")).to(timezone), model=new_sleep_model(data.get("model")), modified=arrow_or_raise(data.get("modified")).to(timezone), startdate=arrow_or_raise(data.get("startdate")).to(timezone), timezone=timezone, data=new_get_sleep_summary_data(dict_or_raise(data.get("data"))), )
Example #16
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def refresh_token(self) -> None: """Manually refresh the token.""" token_dict: Final = self._client.refresh_token( token_url=self._client.auto_refresh_url ) self._update_token(token=token_dict)
Example #17
Source File: main.py From datcord_bot with MIT License | 5 votes |
def delete_edit_timer( msg: Any, time: int, error: bool = False, call_msg: Any = None ) -> None: """ Counts down by editing the response message, then deletes both that one and the original message. """ ws: Final = ":white_small_square:" bs: Final = ":black_small_square:" # Cache the message content. We can't use msg.content in the for # loop as the msg object is mutable (so that we would append a new # line for every loop iteration). msg_text: str = msg.content for i in range(time + 1): await msg.edit(content=msg_text + "\n" + ws * (time - i) + bs * i) await asyncio.sleep(1) await msg.delete() if call_msg: # Prevent crash if the call message has been deleted before the bot # gets to it. try: await call_msg.delete() except: print("Call message does not exist.")
Example #18
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def get_authorize_url(self) -> str: """Generate the authorize url.""" url: Final = str( self._session.authorization_url("%s/%s" % (self.URL, self.PATH_AUTHORIZE))[ 0 ] ) if self._mode: return url + "&mode=" + self._mode return url
Example #19
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def notify_subscribe( self, callbackurl: str, appli: Optional[NotifyAppli] = None, comment: Optional[str] = None, ) -> None: """Subscribe to receive notifications when new data is available.""" params: Final[ParamsType] = {} update_params(params, "callbackurl", callbackurl) update_params(params, "appli", appli, lambda appli: appli.value) update_params(params, "comment", comment) update_params(params, "action", "subscribe") self.request(path=self.PATH_NOTIFY, params=params)
Example #20
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def sleep_get_summary( self, startdateymd: Optional[DateType] = None, enddateymd: Optional[DateType] = None, data_fields: Optional[Iterable[GetSleepSummaryField]] = None, lastupdate: Optional[DateType] = None, ) -> SleepGetSummaryResponse: """Get sleep summary.""" params: Final[ParamsType] = {} update_params( params, "startdateymd", startdateymd, lambda val: arrow.get(val).format("YYYY-MM-DD"), ) update_params( params, "enddateymd", enddateymd, lambda val: arrow.get(val).format("YYYY-MM-DD"), ) update_params( params, "data_fields", data_fields, lambda fields: ",".join([field.value for field in fields]), ) update_params( params, "lastupdate", lastupdate, lambda val: arrow.get(val).timestamp ) update_params(params, "action", "getsummary") return new_sleep_get_summary_response( self.request(path=self.PATH_V2_SLEEP, params=params) )
Example #21
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def measure_get_meas( self, meastype: Optional[MeasureType] = None, category: Optional[MeasureGetMeasGroupCategory] = None, startdate: Optional[DateType] = None, enddate: Optional[DateType] = None, offset: Optional[int] = None, lastupdate: Optional[DateType] = None, ) -> MeasureGetMeasResponse: """Get measures.""" params: Final[ParamsType] = {} update_params(params, "meastype", meastype, lambda val: val.value) update_params(params, "category", category, lambda val: val.value) update_params( params, "startdate", startdate, lambda val: arrow.get(val).timestamp ) update_params(params, "enddate", enddate, lambda val: arrow.get(val).timestamp) update_params(params, "offset", offset) update_params( params, "lastupdate", lastupdate, lambda val: arrow.get(val).timestamp ) update_params(params, "action", "getmeas") return new_measure_get_meas_response( self.request(path=self.PATH_MEASURE, params=params) )
Example #22
Source File: __init__.py From python_withings_api with MIT License | 5 votes |
def measure_get_activity( self, startdateymd: Optional[DateType] = None, enddateymd: Optional[DateType] = None, offset: Optional[int] = None, data_fields: Optional[Iterable[GetActivityField]] = None, lastupdate: Optional[DateType] = None, ) -> MeasureGetActivityResponse: """Get user created activities.""" params: Final[ParamsType] = {} update_params( params, "startdateymd", startdateymd, lambda val: arrow.get(val).format("YYYY-MM-DD"), ) update_params( params, "enddateymd", enddateymd, lambda val: arrow.get(val).format("YYYY-MM-DD"), ) update_params(params, "offset", offset) update_params( params, "data_fields", data_fields, lambda fields: ",".join([field.value for field in fields]), ) update_params( params, "lastupdate", lastupdate, lambda val: arrow.get(val).timestamp ) update_params(params, "action", "getactivity") return new_measure_get_activity_response( self.request(path=self.PATH_V2_MEASURE, params=params) )
Example #23
Source File: test_init.py From python_withings_api with MIT License | 4 votes |
def test_authorize() -> None: """Test function.""" client_id: Final = "fake_client_id" consumer_secret: Final = "fake_consumer_secret" callback_uri: Final = "http://127.0.0.1:8080" arrow.utcnow = MagicMock(return_value=arrow.get(100000000)) responses.add( method=responses.POST, url="https://account.withings.com/oauth2/token", json=_FETCH_TOKEN_RESPONSE_BODY, status=200, ) auth: Final = WithingsAuth( client_id, consumer_secret, callback_uri=callback_uri, scope=(AuthScope.USER_METRICS, AuthScope.USER_ACTIVITY), ) url: Final = auth.get_authorize_url() assert url.startswith("https://account.withings.com/oauth2_user/authorize2") assert_url_query_equals( url, { "response_type": "code", "client_id": "fake_client_id", "redirect_uri": "http://127.0.0.1:8080", "scope": "user.metrics,user.activity", }, ) params: Final = dict(parse.parse_qsl(parse.urlsplit(url).query)) assert "scope" in params assert len(params["scope"]) > 0 creds: Final = auth.get_credentials("FAKE_CODE") assert creds == Credentials( access_token="my_access_token", token_expiry=100000011, token_type="Bearer", refresh_token="my_refresh_token", userid=_USERID, client_id=client_id, consumer_secret=consumer_secret, )
Example #24
Source File: test_init.py From python_withings_api with MIT License | 4 votes |
def test_refresh_token() -> None: """Test function.""" client_id: Final = "my_client_id" consumer_secret: Final = "my_consumer_secret" credentials: Final = Credentials( access_token="my_access_token,_old", token_expiry=arrow.utcnow().timestamp - 1, token_type="Bearer", refresh_token="my_refresh_token_old", userid=_USERID, client_id=client_id, consumer_secret=consumer_secret, ) responses.add( method=responses.POST, url=re.compile("https://account.withings.com/oauth2/token.*"), status=200, json=_FETCH_TOKEN_RESPONSE_BODY, ) responses.add( method=responses.POST, url=re.compile("https://account.withings.com/oauth2/token.*"), status=200, json={ "access_token": "my_access_token_refreshed", "expires_in": 11, "token_type": "Bearer", "refresh_token": "my_refresh_token_refreshed", "userid": _USERID, }, ) responses_add_measure_get_activity() refresh_callback: Final = MagicMock() api: Final = WithingsApi(credentials, refresh_callback) api.measure_get_activity() refresh_callback.assert_called_with(api.get_credentials()) new_credentials1: Final = api.get_credentials() assert new_credentials1.access_token == "my_access_token" assert new_credentials1.refresh_token == "my_refresh_token" assert new_credentials1.token_expiry > credentials.token_expiry refresh_callback.reset_mock() api.refresh_token() refresh_callback.assert_called_with(api.get_credentials()) new_credentials2: Final = api.get_credentials() assert new_credentials2.access_token == "my_access_token_refreshed" assert new_credentials2.refresh_token == "my_refresh_token_refreshed" assert new_credentials2.token_expiry > credentials.token_expiry
Example #25
Source File: cloudpickle.py From ray with Apache License 2.0 | 4 votes |
def _save_parametrized_type_hint(self, obj): # The distorted type check sematic for typing construct becomes: # ``type(obj) is type(TypeHint)``, which means "obj is a # parametrized TypeHint" if type(obj) is type(Literal): # pragma: no branch initargs = (Literal, obj.__values__) elif type(obj) is type(Final): # pragma: no branch initargs = (Final, obj.__type__) elif type(obj) is type(ClassVar): initargs = (ClassVar, obj.__type__) elif type(obj) is type(Generic): parameters = obj.__parameters__ if len(obj.__parameters__) > 0: # in early Python 3.5, __parameters__ was sometimes # preferred to __args__ initargs = (obj.__origin__, parameters) else: initargs = (obj.__origin__, obj.__args__) elif type(obj) is type(Union): if sys.version_info < (3, 5, 3): # pragma: no cover initargs = (Union, obj.__union_params__) else: initargs = (Union, obj.__args__) elif type(obj) is type(Tuple): if sys.version_info < (3, 5, 3): # pragma: no cover initargs = (Tuple, obj.__tuple_params__) else: initargs = (Tuple, obj.__args__) elif type(obj) is type(Callable): if sys.version_info < (3, 5, 3): # pragma: no cover args = obj.__args__ result = obj.__result__ if args != Ellipsis: if isinstance(args, tuple): args = list(args) else: args = [args] else: (*args, result) = obj.__args__ if len(args) == 1 and args[0] is Ellipsis: args = Ellipsis else: args = list(args) initargs = (Callable, (args, result)) else: # pragma: no cover raise pickle.PicklingError( "Cloudpickle Error: Unknown type {}".format(type(obj)) ) self.save_reduce(_create_parametrized_type_hint, initargs, obj=obj) # Tornado support