Skip to content

Commit

Permalink
added new helper class Obj_Id
Browse files Browse the repository at this point in the history
  • Loading branch information
DinisCruz committed Jan 21, 2025
1 parent b545677 commit 5de319a
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 4 deletions.
29 changes: 29 additions & 0 deletions osbot_utils/helpers/Obj_Id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import random

_hex_table = [f"{i:02x}" for i in range(256)]

def is_obj_id(value: str):
var_type = type(value)
if var_type is Obj_Id:
return True
if var_type is str:
if len(value) == 8: # todo: add efficient check if we only have hex values
return True
return False

def new_obj_id():
return hex(random.getrandbits(32))[2:].zfill(8) # slice off '0x' and pad

class Obj_Id(str):
def __new__(cls, value: str=None):
if value:
if is_obj_id(value):
obj_id = value
else:
raise ValueError(f'in Obj_Id: value provided was not a valid Obj_Id: {value}')
else:
obj_id = new_obj_id()
return super().__new__(cls, obj_id) # Return a new instance of Guid initialized with the string version of the UUID

def __str__(self):
return self
21 changes: 20 additions & 1 deletion osbot_utils/testing/performance/Performance_Measure__Session.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,23 @@ def assert_time(self, *expected_time: int):
new_expected_time = last_expected_time * 5 # using last_expected_time * 5 as the upper limit (since these tests are significantly slowed in GitHUb Actions)
assert last_expected_time <= self.result.final_score <= new_expected_time, f"Performance changed for {self.result.name}: expected {last_expected_time} < {self.result.final_score:,d}ns, expected {new_expected_time}"
else:
assert self.result.final_score in expected_time, f"Performance changed for {self.result.name}: got {self.result.final_score:,d}ns, expected {expected_time}"
assert self.result.final_score in expected_time, f"Performance changed for {self.result.name}: got {self.result.final_score:,d}ns, expected {expected_time}"

def assert_time(self, *expected_time: int): # Assert that the final score matches the expected normalized time"""
if self.assert_enabled is False:
return
if in_github_action():
last_expected_time = expected_time[-1] + 100 # +100 in case it is 0
new_expected_time = last_expected_time * 5 # using last_expected_time * 5 as the upper limit (since these tests are significantly slowed in GitHUb Actions)
assert last_expected_time <= self.result.final_score <= new_expected_time, f"Performance changed for {self.result.name}: expected {last_expected_time} < {self.result.final_score:,d}ns, expected {new_expected_time}"
else:
assert self.result.final_score in expected_time, f"Performance changed for {self.result.name}: got {self.result.final_score:,d}ns, expected {expected_time}"

def assert_time__less_than(self, max_time: int): # Assert that the final score matches the expected normalized time"""
if self.assert_enabled is False:
return
if in_github_action():
max_time = max_time * 5 # adjust for GitHub's slowness

assert self.result.final_score <= max_time, f"Performance changed for {self.result.name}: got {self.result.final_score:,d}ns, expected less than {max_time}ns"

3 changes: 2 additions & 1 deletion osbot_utils/type_safe/shared/Type_Safe__Convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ def convert_to_value_from_obj_annotation(self, target, attr_name, value):
from osbot_utils.helpers.Random_Guid import Random_Guid
from osbot_utils.helpers.Safe_Id import Safe_Id
from osbot_utils.helpers.Str_ASCII import Str_ASCII
from osbot_utils.helpers.Obj_Id import Obj_Id

TYPE_SAFE__CONVERT_VALUE__SUPPORTED_TYPES = [Guid, Random_Guid, Safe_Id, Str_ASCII, Timestamp_Now]
TYPE_SAFE__CONVERT_VALUE__SUPPORTED_TYPES = [Guid, Random_Guid, Safe_Id, Str_ASCII, Timestamp_Now, Obj_Id]

if target is not None and attr_name is not None:
if hasattr(target, '__annotations__'):
Expand Down
8 changes: 6 additions & 2 deletions osbot_utils/type_safe/steps/Type_Safe__Step__Class_Kwargs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Dict, Any, Type

from osbot_utils.helpers.Obj_Id import Obj_Id
from osbot_utils.helpers.Random_Guid import Random_Guid
from osbot_utils.type_safe.shared.Type_Safe__Cache import Type_Safe__Cache, type_safe_cache
from osbot_utils.type_safe.shared.Type_Safe__Shared__Variables import IMMUTABLE_TYPES
Expand Down Expand Up @@ -43,8 +45,10 @@ def is_kwargs_cacheable(self, cls, kwargs: Dict[str, Any]) -> bool:
match = all(isinstance(value, IMMUTABLE_TYPES) for value in kwargs.values())

if match: # check for special cases that we can't cache (like Random_Guid)
if Random_Guid in list(dict(annotations).values()): # todo: need to add the other special cases (like Timestamp_Now)

annotations_types = list(dict(annotations).values())
if Random_Guid in annotations_types: # todo: need to add the other special cases (like Timestamp_Now)
return False
if Obj_Id in annotations_types: # we can't cache Obj_id, since this would give us the same ID everutime
return False
return match

Expand Down
27 changes: 27 additions & 0 deletions tests/unit/helpers/test_Obj_Id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from unittest import TestCase

from osbot_utils.helpers.Obj_Id import new_obj_id, is_obj_id, Obj_Id
from osbot_utils.testing.performance.Performance_Measure__Session import Performance_Measure__Session
from osbot_utils.utils.Dev import pprint


class test_Obj_Id(TestCase):

def test__new__(self):
obj_id = Obj_Id()
assert type(obj_id ) is Obj_Id
assert isinstance(obj_id, str) is True
assert is_obj_id(obj_id ) is True

def test_new_obj_id(self):
obj_id = new_obj_id()
assert is_obj_id(obj_id)

def test__perf__new__(self):
with Performance_Measure__Session() as _:
_.measure(lambda: Obj_Id() ).assert_time__less_than(600)

def test__perf__new_obj_id(self):
with Performance_Measure__Session() as _:
_.measure(lambda: new_obj_id() ).assert_time__less_than(300)
_.measure(lambda: is_obj_id('abc')).assert_time__less_than(300)

0 comments on commit 5de319a

Please sign in to comment.