Clean up object naming

Honor the upstream names for objects if they've been given them, use
the automatic variable magic as a fallback.  And in the case of truly
anonymous objects, give them a name based on their type (e.g. "Box3")
vs. "_unknown_var99".
This commit is contained in:
Andy Ross
2025-07-02 09:27:13 -07:00
parent 05963d58f2
commit 7f43367459

View File

@@ -382,19 +382,30 @@ def _preprocess_cad(obj: CADLike, **kwargs) -> CADCoreLike:
return obj return obj
_find_var_name_count = 0 _obj_name_counts = {}
def _find_var_name(obj: any, avoid_levels: int = 2) -> str: def _find_var_name(obj: any, avoid_levels: int = 2) -> str:
"""A hacky way to get a stable name for an object that may change over time""" """A hacky way to get a stable name for an object that may change over time"""
global _find_var_name_count
# Build123d objects have a "label" property, CadQuery Assembly's have "name"
for f in ('label', 'name'):
if hasattr(obj, f):
v = getattr(obj, f)
if v != '':
return v;
# Otherwise walk up our stack to see if there's a local variable that points to it
obj_shape = get_shape(obj, error=False) or obj obj_shape = get_shape(obj, error=False) or obj
for frame in inspect.stack()[avoid_levels:]: for frame in inspect.stack()[avoid_levels:]:
for key, value in frame.frame.f_locals.items(): for key, value in frame.frame.f_locals.items():
if get_shape(value, error=False) is obj_shape: if get_shape(value, error=False) is obj_shape:
return key return key
_find_var_name_count += 1
return 'unknown_var_' + str(_find_var_name_count) # Last resort, name it for its type with a disambiguating number
global _obj_name_counts
t = obj.__class__.__name__
_obj_name_counts[t] = 1 if t not in _obj_name_counts else _obj_name_counts[t] + 1
return t + str(_obj_name_counts[t])
def sizeof_fmt(num, suffix="B"): def sizeof_fmt(num, suffix="B"):