dc-cmnutils 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,814 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 对象功能类 (ObjectHelper)
4
+ 提供一系列静态方法用于对象判断、类型检查、空值处理和比较操作。
5
+ """
6
+
7
+ from typing import Any, Iterable, TypeVar, Generic, Optional, Union, Callable
8
+ from collections.abc import Iterable as ABCIterable
9
+ import numbers
10
+ import decimal
11
+ import datetime
12
+
13
+ T = TypeVar('T')
14
+ import copy
15
+ import sys
16
+ from typing import Any, Dict, List, Optional, TypeVar, get_type_hints
17
+ from dc.cmnlib.basicdata.object import ObjectHelper
18
+ # T = TypeVar('T')
19
+
20
+ class ObjectUtils(ObjectHelper):
21
+ """
22
+ 封装常用的 Python Object 操作工具类。
23
+ 所有方法均为静态方法,无需实例化即可使用。
24
+ 对象功能辅助类,提供类似于 C# dotNetExt.Object 的扩展方法。
25
+ """
26
+ @staticmethod
27
+ def is_null(obj: Any) -> bool:
28
+ """
29
+ 判断对象是否为 None。
30
+
31
+ Args:
32
+ obj: 任意对象
33
+
34
+ Returns:
35
+ bool: 如果对象为 None 返回 True,否则返回 False。
36
+ """
37
+ return obj is None
38
+
39
+ @staticmethod
40
+ def is_not_null(obj: Any) -> bool:
41
+ """
42
+ 判断对象是否不为 None。
43
+
44
+ Args:
45
+ obj: 任意对象
46
+
47
+ Returns:
48
+ bool: 如果对象不为 None 返回 True,否则返回 False。
49
+ """
50
+ return not ObjectUtils.is_null(obj)
51
+
52
+
53
+
54
+
55
+ @staticmethod
56
+ def is_blank(obj: Any) -> bool:
57
+ """判断对象是否为 None 或空白字符串。
58
+
59
+ 与 is_null 的区别:只检查 None 和空字符串,
60
+ 不检查容器类型(list/dict/set 等)和数值类型。
61
+
62
+ Args:
63
+ obj: 待判断的对象
64
+
65
+ Returns:
66
+ bool: 对象为 None 或空白字符串时返回 True
67
+ """
68
+ if obj is None:
69
+ return True
70
+ if isinstance(obj, str) and obj.strip() == "":
71
+ return True
72
+ return False
73
+
74
+ @staticmethod
75
+ def is_not_blank(obj: Any) -> bool:
76
+ """判断对象是否不为 None 且非空白字符串。
77
+
78
+ 这是 is_blank 的补集方法。
79
+
80
+ Args:
81
+ obj: 待判断的对象
82
+
83
+ Returns:
84
+ bool: 对象非空且非空白时返回 True,否则返回 False
85
+ """
86
+ return not ObjectUtils.is_blank(obj)
87
+
88
+ # ==================== 相等比较方法 ====================
89
+
90
+ @staticmethod
91
+ def is_equal(obj1: Any, obj2: Any) -> bool:
92
+ """判断两个对象是否相等。
93
+
94
+ 该方法比直接使用 == 更加健壮,能够处理以下边界情况:
95
+ - obj1 和 obj2 均为 None 时,返回 True
96
+ - 其中一个为 None,另一个不为 None 时,返回 False
97
+ - 使用 == 运算符进行值比较
98
+
99
+ Args:
100
+ obj1: 第一个对象
101
+ obj2: 第二个对象
102
+
103
+ Returns:
104
+ bool: 两个对象相等时返回 True,否则返回 False
105
+
106
+ Examples:
107
+ >>> ObjectUtils.is_equal("hello", "hello")
108
+ True
109
+ >>> ObjectUtils.is_equal(None, None)
110
+ True
111
+ >>> ObjectUtils.is_equal(None, "hello")
112
+ False
113
+ >>> ObjectUtils.is_equal([1, 2], [1, 2])
114
+ True
115
+ """
116
+ if ObjectUtils.is_null(obj1) and (ObjectUtils.is_null(obj2)):
117
+ return True
118
+ if ObjectUtils.is_null(obj1) or ObjectUtils.is_null(obj2):
119
+ return False
120
+ try:
121
+ return obj1 == obj2
122
+ except Exception:
123
+ # 如果 == 比较抛出异常(某些自定义类可能未实现 __eq__),
124
+ # 退化为比较内存地址
125
+ return obj1 is obj2
126
+
127
+ @staticmethod
128
+ def is_not_equal(obj1: Any, obj2: Any) -> bool:
129
+ """判断两个对象是否不相等。
130
+
131
+ 这是 is_equal 的补集方法。
132
+
133
+ Args:
134
+ obj1: 第一个对象
135
+ obj2: 第二个对象
136
+
137
+ Returns:
138
+ bool: 两个对象不相等时返回 True,否则返回 False
139
+ """
140
+ return not ObjectUtils.is_equal(obj1, obj2)
141
+
142
+ @staticmethod
143
+ def is_deep_equal(obj1: Any, obj2: Any) -> bool:
144
+ """判断两个对象是否深度相等(递归比较嵌套结构)。
145
+
146
+ 对于列表、元组、字典、集合等容器类型,会递归比较其中的元素。
147
+ 对于自定义对象,会比较它们的 __dict__ 属性字典。
148
+
149
+ Args:
150
+ obj1: 第一个对象
151
+ obj2: 第二个对象
152
+
153
+ Returns:
154
+ bool: 两个对象深度相等时返回 True,否则返回 False
155
+
156
+ Examples:
157
+ >>> ObjectUtils.is_deep_equal({"a": [1, 2]}, {"a": [1, 2]})
158
+ True
159
+ >>> ObjectUtils.is_deep_equal([1, [2, 3]], [1, [2, 3]])
160
+ True
161
+ >>> ObjectUtils.is_deep_equal({"a": 1}, {"a": 2})
162
+ False
163
+ """
164
+ if obj1 is None and obj2 is None:
165
+ return True
166
+ if obj1 is None or obj2 is None:
167
+ return False
168
+
169
+ # 类型不同直接返回 False
170
+ if type(obj1) is not type(obj2):
171
+ return False
172
+
173
+ # 基本类型直接用 == 比较
174
+ if isinstance(obj1, (str, int, float, bool, bytes)):
175
+ return obj1 == obj2
176
+
177
+ # 集合类型
178
+ if isinstance(obj1, (set, frozenset)):
179
+ if len(obj1) != len(obj2):
180
+ return False
181
+ return all(any(ObjectUtils.is_deep_equal(a, b) for b in obj2) for a in obj1)
182
+
183
+ # 列表和元组
184
+ if isinstance(obj1, (list, tuple)):
185
+ if len(obj1) != len(obj2):
186
+ return False
187
+ return all(
188
+ ObjectUtils.is_deep_equal(a, b) for a, b in zip(obj1, obj2)
189
+ )
190
+
191
+ # 字典
192
+ if isinstance(obj1, dict):
193
+ if len(obj1) != len(obj2):
194
+ return False
195
+ return all(
196
+ k in obj2 and ObjectUtils.is_deep_equal(v, obj2[k])
197
+ for k, v in obj1.items()
198
+ )
199
+
200
+ # 自定义对象:比较 __dict__
201
+ if hasattr(obj1, "__dict__") and hasattr(obj2, "__dict__"):
202
+ return ObjectUtils.is_deep_equal(obj1.__dict__, obj2.__dict__)
203
+
204
+ # 其他类型退化为 == 比较
205
+ try:
206
+ return obj1 == obj2
207
+ except Exception:
208
+ return obj1 is obj2
209
+
210
+ # ==================== 对象复制方法 ====================
211
+
212
+ @staticmethod
213
+ def deep_copy(obj: Any) -> Any:
214
+ """对对象进行深拷贝。
215
+
216
+ Args:
217
+ obj: 待深拷贝的对象
218
+
219
+ Returns:
220
+ 深拷贝后的新对象,如果 obj 为 None 则返回 None
221
+ """
222
+ if obj is None:
223
+ return None
224
+ return copy.deepcopy(obj)
225
+
226
+ @staticmethod
227
+ def shallow_copy(obj: Any) -> Any:
228
+ """对对象进行浅拷贝。
229
+
230
+ Args:
231
+ obj: 待浅拷贝的对象
232
+
233
+ Returns:
234
+ 浅拷贝后的新对象,如果 obj 为 None 则返回 None
235
+ """
236
+ if obj is None:
237
+ return None
238
+ if isinstance(obj, (list, tuple, dict, set)):
239
+ return type(obj)(obj)
240
+ return obj
241
+
242
+ # ==================== 对象信息方法 ====================
243
+
244
+ @staticmethod
245
+ def to_dict(obj: Any) -> Optional[dict]:
246
+ """将对象转换为字典。
247
+
248
+ 读取对象的 __dict__ 属性,将其转换为普通字典。
249
+ 如果对象没有 __dict__ 属性,返回 None。
250
+
251
+ Args:
252
+ obj: 待转换的对象
253
+
254
+ Returns:
255
+ 对象的属性字典,如果无法转换则返回 None
256
+ """
257
+ if obj is None:
258
+ return None
259
+ if hasattr(obj, "__dict__"):
260
+ return obj.__dict__
261
+ return None
262
+
263
+ @staticmethod
264
+ def get_type_name(obj: Any) -> str:
265
+ """获取对象的类型名称。
266
+
267
+ Args:
268
+ obj: 任意对象
269
+
270
+ Returns:
271
+ 对象的类名,如 'str'、'int'、'list' 等
272
+ """
273
+ if obj is None:
274
+ return "NoneType"
275
+ return type(obj).__name__
276
+
277
+ @staticmethod
278
+ def safe_str(obj: Any, default: str = "") -> str:
279
+ """安全地将对象转换为字符串。
280
+
281
+ 如果对象为 None,返回指定的默认值。
282
+
283
+ Args:
284
+ obj: 待转换的对象
285
+ default: None 时的默认返回值,默认为空字符串
286
+
287
+ Returns:
288
+ 对象的字符串表示,None 时返回 default
289
+ """
290
+ if obj is None:
291
+ return default
292
+ return str(obj)
293
+
294
+ @staticmethod
295
+ def equals_any(obj: Any, *targets: Any) -> bool:
296
+ """判断对象是否等于目标值列表中的任意一个。
297
+
298
+ Args:
299
+ obj: 待比较的对象
300
+ *targets: 一个或多个目标值
301
+
302
+ Returns:
303
+ bool: obj 等于 targets 中任意一个值时返回 True
304
+ """
305
+ return any(ObjectUtils.is_equal(obj, t) for t in targets)
306
+
307
+ @staticmethod
308
+ def is_in(obj: Any, container: Any) -> bool:
309
+ """判断对象是否存在于容器(列表/元组/集合/字典键)中。
310
+
311
+ 与 is_equal 配合使用,支持自定义类的相等判断。
312
+
313
+ Args:
314
+ obj: 待查找的对象
315
+ container: 容器对象(list/tuple/set/dict)
316
+
317
+ Returns:
318
+ bool: 对象存在于容器中时返回 True
319
+
320
+ Raises:
321
+ TypeError: 如果 container 不是支持的容器类型
322
+ """
323
+ if not isinstance(container, (list, tuple, set, frozenset, dict)):
324
+ raise TypeError(f"不支持的容器类型: {type(container).__name__}")
325
+ if isinstance(container, dict):
326
+ return any(ObjectUtils.is_equal(obj, k) for k in container.keys())
327
+ return any(ObjectUtils.is_equal(obj, item) for item in container)
328
+
329
+ @staticmethod
330
+ def is_date(obj: Any) -> bool:
331
+ """
332
+ 判断对象是否为 datetime 对象。
333
+
334
+ Args:
335
+ obj: 任意对象
336
+
337
+ Returns:
338
+ bool: 如果是 datetime 对象返回 True。
339
+ """
340
+ return isinstance(obj, datetime.datetime)
341
+
342
+
343
+
344
+ @staticmethod
345
+ def is_null_or_empty(data: Any) -> bool:
346
+ """
347
+ 判断对象是否为 null、空字符串、DBNull 或空集合。
348
+
349
+ Args:
350
+ data: 要验证的对象
351
+
352
+ Returns:
353
+ bool: 为空或空集合返回 True。
354
+ """
355
+ if ObjectUtils.is_null(data):
356
+ return True
357
+ if isinstance(data, str):
358
+ return len(data.strip()) == 0
359
+ if isinstance(data, ABCIterable):
360
+ # 尝试判断是否可迭代且为空
361
+ try:
362
+ # 对于字典、列表、元组等直接判断
363
+ return len(data) == 0
364
+ except TypeError:
365
+ # 对于不支持 len() 的生成器,消耗它来判断
366
+ # 注意:这会消耗生成器,但在大多数数据验证场景下,传入的通常是 list/dict
367
+ return not any(True for _ in data)
368
+ return False
369
+
370
+ @staticmethod
371
+ def is_not_null_or_empty(data: Any) -> bool:
372
+ """
373
+ 判断对象是否不为空 (非 null, 非空字符串, 非空集合)。
374
+
375
+ Args:
376
+ data: 要验证的对象
377
+
378
+ Returns:
379
+ bool: 不为空返回 True。
380
+ """
381
+ return not ObjectUtils.is_null_or_empty(data)
382
+
383
+ @staticmethod
384
+ def are_different(value: T, new_value: T) -> bool:
385
+ """
386
+ 比较两个对象是否不相等,防止空值异常。
387
+
388
+ Args:
389
+ value: 原值
390
+ new_value: 新值
391
+
392
+ Returns:
393
+ bool: 如果两个值不相等返回 True。
394
+ """
395
+ return value != new_value
396
+
397
+ @staticmethod
398
+ def is_null_or_db_null(obj: Any) -> bool:
399
+ """
400
+ 确定对象是否为 null 或 DBNull。
401
+
402
+ Args:
403
+ obj: 任意对象
404
+
405
+ Returns:
406
+ bool: 如果是 None 返回 True。
407
+ """
408
+ return obj is None
409
+
410
+ @staticmethod
411
+ def is_type(obj: Any, type_: type) -> bool:
412
+ """
413
+ 判断对象是否为指定类型。
414
+
415
+ Args:
416
+ obj: 任意对象
417
+ type_: 目标类型 (如 str, int)
418
+
419
+ Returns:
420
+ bool: 如果类型匹配返回 True。
421
+ """
422
+ if ObjectUtils.is_null(obj):
423
+ return False
424
+ return type(obj) is type_
425
+
426
+ @staticmethod
427
+ def is_array(obj: Any) -> bool:
428
+ """
429
+ 判断对象是否为数组 (在 Python 中通常指 list 或 tuple)。
430
+
431
+ Args:
432
+ obj: 任意对象
433
+
434
+ Returns:
435
+ bool: 如果是 list 或 tuple 返回 True。
436
+ """
437
+ return isinstance(obj, (list, tuple))
438
+
439
+ @staticmethod
440
+ def is_reference_null(obj: Any) -> bool:
441
+ """
442
+ 检查引用是否为 null (None)。
443
+
444
+ Args:
445
+ obj: 任意对象
446
+
447
+ Returns:
448
+ bool: 如果是 None 返回 True。
449
+ """
450
+ return obj is None
451
+
452
+ @staticmethod
453
+ def is_not_reference_null(obj: Any) -> bool:
454
+ """
455
+ 检查引用是否不为 null (None)。
456
+
457
+ Args:
458
+ obj: 任意对象
459
+
460
+ Returns:
461
+ bool: 如果不是 None 返回 True。
462
+ """
463
+ return obj is not None
464
+
465
+ @staticmethod
466
+ def is_not_empty(value: Any) -> bool:
467
+ """
468
+ 针对值类型 (struct) 的非空判断。
469
+ 在 Python 中,通常指非默认值 (如 0, False)。
470
+
471
+ Args:
472
+ value: 值类型对象
473
+
474
+ Returns:
475
+ bool: 如果不等于其类型的默认值返回 True。
476
+ """
477
+ # Python 没有 struct 的概念,这里简单判断是否为 "真" 值
478
+ # 或者判断是否等于该类型的典型默认值 (0, False, 0.0)
479
+ return bool(value) or value != type(value)()
480
+
481
+ @staticmethod
482
+ def is_numeric(obj: Any) -> bool:
483
+ """
484
+ 判断对象是否为数字类型。
485
+ 包括: int, float, complex, decimal.Decimal 等。
486
+
487
+ Args:
488
+ obj: 任意对象
489
+
490
+ Returns:
491
+ bool: 如果是数字类型返回 True。
492
+ """
493
+ if obj is None:
494
+ return False
495
+ # 检查是否为 Python 内置数字类型或 decimal
496
+ return isinstance(obj, (int, float, complex, decimal.Decimal)) or isinstance(obj, numbers.Number)
497
+
498
+ @staticmethod
499
+ def is_numeric_type(obj: Any) -> bool:
500
+ """
501
+ 判断对象的类型是否为数值类型 (基于类型码)。
502
+ 这是一个更严格的检查。
503
+
504
+ Args:
505
+ obj: 任意对象
506
+
507
+ Returns:
508
+ bool: 如果是数值类型返回 True。
509
+ """
510
+ if obj is None:
511
+ return False
512
+ obj_type = type(obj)
513
+ # 模拟 C# 的 TypeCode 检查
514
+ numeric_types = (
515
+ int, float, complex, decimal.Decimal,
516
+ # Python 中的 bool 也是 int 的子类,通常也视为数值
517
+ bool
518
+ )
519
+ return obj_type in numeric_types or issubclass(obj_type, numbers.Number)
520
+
521
+ # region Coalesce (空值合并)
522
+
523
+ @staticmethod
524
+ def coalesce_db_null(value: Any, alternative: T) -> Union[Any, T]:
525
+ """
526
+ 如果源值为 None (DBNull),则返回替代值。
527
+
528
+ Args:
529
+ value: 源值
530
+ alternative: 替代值
531
+
532
+ Returns:
533
+ Any: 源值或替代值。
534
+ """
535
+ return alternative if value is None else value
536
+
537
+ @staticmethod
538
+ def coalesce_db_null_default(value: Any, default: Any = None) -> Any:
539
+ """
540
+ 如果源值为 None (DBNull),则返回默认值 (None)。
541
+
542
+ Args:
543
+ value: 源值
544
+ default: 默认值
545
+
546
+ Returns:
547
+ Any: 源值或默认值。
548
+ """
549
+ return ObjectUtils.coalesce_db_null(value, default)
550
+
551
+ # endregion
552
+
553
+ # region Equals (相等判断)
554
+
555
+ @staticmethod
556
+ def equals(obj_a: Any, obj_b: Any) -> bool:
557
+ """
558
+ 判断两个对象是否相等。
559
+
560
+ Args:
561
+ obj_a: 对象 A
562
+ obj_b: 对象 B
563
+
564
+ Returns:
565
+ bool: 如果相等返回 True。
566
+ """
567
+ # 引用相等 (包括都为 None 的情况)
568
+ if obj_a is obj_b:
569
+ return True
570
+ # 其中一个为 None
571
+ if obj_a is None or obj_b is None:
572
+ return False
573
+ # 调用对象的 __eq__ 方法
574
+ return obj_a == obj_b
575
+
576
+ @staticmethod
577
+ def equals_any(self: Any, others: Iterable[Any]) -> bool:
578
+ """
579
+ 判断对象是否等于列表中的任意一个对象。
580
+
581
+ Args:
582
+ self: 当前对象
583
+ others: 对象列表
584
+
585
+ Returns:
586
+ bool: 如果等于列表中任意一个返回 True。
587
+ """
588
+ if not others:
589
+ return False
590
+ return any(ObjectUtils.equals(self, item) for item in others)
591
+
592
+ # endregion
593
+
594
+ # region IsInCollection (集合包含判断)
595
+
596
+ @staticmethod
597
+ def is_in_collection(value: T, collection: Union[Iterable[T], None]) -> bool:
598
+ """
599
+ 判断对象是否在列表/集合中。
600
+
601
+ Args:
602
+ value: 要查找的值
603
+ collection: 集合 (列表, 元组, 集合等)
604
+
605
+ Returns:
606
+ bool: 如果在集合中返回 True。
607
+ """
608
+ if collection is None:
609
+ return False
610
+ # 对于字典,检查 key
611
+ if isinstance(collection, dict):
612
+ return value in collection
613
+ # 对于其他可迭代对象
614
+ try:
615
+ return value in collection
616
+ except TypeError:
617
+ # 如果集合不支持 in 操作 (如生成器),进行遍历
618
+ for item in collection:
619
+ if ObjectUtils.equals(value, item):
620
+ return True
621
+ return False
622
+
623
+ @staticmethod
624
+ def is_not_in_collection(value: T, collection: Union[Iterable[T], None]) -> bool:
625
+ """
626
+ 判断对象是否不在列表/集合中。
627
+
628
+ Args:
629
+ value: 要查找的值
630
+ collection: 集合
631
+
632
+ Returns:
633
+ bool: 如果不在集合中返回 True。
634
+ """
635
+ return not ObjectUtils.is_in_collection(value, collection)
636
+
637
+ # endregion
638
+
639
+ # region IsBetween (范围判断)
640
+
641
+ @staticmethod
642
+ def is_between(value: T, min_value: T, max_value: T,
643
+ include_lower_bound: bool = True,
644
+ include_upper_bound: bool = True) -> bool:
645
+ """
646
+ 判断值是否在最小值和最大值之间。
647
+
648
+ Args:
649
+ value: 当前值
650
+ min_value: 最小值
651
+ max_value: 最大值
652
+ include_lower_bound: 是否包含下限
653
+ include_upper_bound: 是否包含上限
654
+
655
+ Returns:
656
+ bool: 如果在范围内返回 True。
657
+ """
658
+ # 处理下限比较
659
+ if include_lower_bound:
660
+ b1 = min_value <= value
661
+ else:
662
+ b1 = min_value < value
663
+
664
+ # 处理上限比较
665
+ if include_upper_bound:
666
+ b2 = value <= max_value
667
+ else:
668
+ b2 = value < max_value
669
+
670
+ return b1 and b2
671
+
672
+ @staticmethod
673
+ def is_between_comparer(value: T, min_value: T, max_value: T,
674
+ comparer: Optional[Callable[[T, T], int]] = None) -> bool:
675
+ """
676
+ 使用比较器判断值是否在范围内 (包含边界)。
677
+
678
+ Args:
679
+ value: 当前值
680
+ min_value: 最小值
681
+ max_value: 最大值
682
+ comparer: 比较函数 (类似 C# 的 IComparer)。
683
+ 如果未提供,使用默认比较。
684
+
685
+ Returns:
686
+ bool: 如果在范围内返回 True。
687
+ """
688
+ # 模拟 C# 的 Comparer<T>.Default
689
+ # 在 Python 中,我们直接使用 <= >= 进行比较
690
+ # 如果提供了自定义比较器,它应该返回 -1, 0, 1
691
+ if comparer is None:
692
+ return ObjectUtils.is_between(value, min_value, max_value)
693
+
694
+ # 自定义比较器逻辑
695
+ # comparer(a, b) 应该返回负数(a<b), 0(相等), 正数(a>b)
696
+ min_max_cmp = comparer(min_value, max_value)
697
+
698
+ if min_max_cmp < 0:
699
+ # min < max
700
+ return comparer(value, min_value) >= 0 and comparer(value, max_value) <= 0
701
+ else:
702
+ # min >= max (反向范围)
703
+ return comparer(value, max_value) >= 0 and comparer(value, min_value) <= 0
704
+
705
+ # endregion
706
+
707
+ @staticmethod
708
+ def safe_getattr(obj: Any, attr: str, default: Any = None) -> Any:
709
+ """
710
+ 安全地获取对象属性,支持嵌套属性(如 'a.b.c')。
711
+ 如果路径中任意一层不存在,返回默认值。
712
+ """
713
+ attrs = attr.split('.')
714
+ current = obj
715
+ for a in attrs:
716
+ try:
717
+ current = getattr(current, a)
718
+ except AttributeError:
719
+ return default
720
+ return current
721
+
722
+ @staticmethod
723
+ def safe_setattr(obj: Any, attr: str, value: Any) -> None:
724
+ """
725
+ 安全地设置对象属性,支持嵌套属性(如 'a.b.c')。
726
+ 如果中间路径不存在,会自动创建空对象占位(使用简单的 Namespace)。
727
+ """
728
+ attrs = attr.split('.')
729
+ current = obj
730
+ for a in attrs[:-1]:
731
+ if not hasattr(current, a):
732
+ # 动态创建一个简单的占位对象
733
+ class _Placeholder: pass
734
+ setattr(current, a, _Placeholder())
735
+ current = getattr(current, a)
736
+ setattr(current, attrs[-1], value)
737
+
738
+ @staticmethod
739
+ def to_dict(obj: Any, exclude_private: bool = True, exclude_none: bool = False) -> Dict[str, Any]:
740
+ """
741
+ 将对象转换为字典。
742
+ :param exclude_private: 是否排除以 _ 开头的私有属性
743
+ :param exclude_none: 是否排除值为 None 的属性
744
+ """
745
+ if obj is None:
746
+ return {}
747
+
748
+ result = {}
749
+ # 优先获取 __dict__,如果没有则尝试 dir()
750
+ keys = getattr(obj, '__dict__', None)
751
+ if keys is not None:
752
+ items = keys.items()
753
+ else:
754
+ items = ((k, getattr(obj, k)) for k in dir(obj) if not callable(getattr(obj, k, None)))
755
+
756
+ for k, v in items:
757
+ if exclude_private and k.startswith('_'):
758
+ continue
759
+ if exclude_none and v is None:
760
+ continue
761
+ result[k] = v
762
+ return result
763
+
764
+ @staticmethod
765
+ def deep_copy(obj: T) -> T:
766
+ """深拷贝对象"""
767
+ return copy.deepcopy(obj)
768
+
769
+ @staticmethod
770
+ def shallow_copy(obj: T) -> T:
771
+ """浅拷贝对象"""
772
+ return copy.copy(obj)
773
+
774
+ @staticmethod
775
+ def get_size(obj: Any, seen: Optional[set] = None) -> int:
776
+ """
777
+ 递归计算对象占用的内存大小(字节)。
778
+ 注意:对于包含循环引用的复杂对象,结果可能不完全精确。
779
+ """
780
+ size = sys.getsizeof(obj)
781
+ if seen is None:
782
+ seen = set()
783
+
784
+ obj_id = id(obj)
785
+ if obj_id in seen:
786
+ return 0
787
+ seen.add(obj_id)
788
+
789
+ if isinstance(obj, dict):
790
+ size += sum([ObjectUtils.get_size(v, seen) for v in obj.values()])
791
+ size += sum([ObjectUtils.get_size(k, seen) for k in obj.keys()])
792
+ elif hasattr(obj, '__dict__'):
793
+ size += ObjectUtils.get_size(obj.__dict__, seen)
794
+ elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
795
+ size += sum([ObjectUtils.get_size(i, seen) for i in obj])
796
+
797
+ return size
798
+
799
+ @staticmethod
800
+ def has_method(obj: Any, method_name: str) -> bool:
801
+ """检查对象是否具有某个可调用的方法"""
802
+ return callable(getattr(obj, method_name, None))
803
+
804
+ @staticmethod
805
+ def merge_attrs(target: Any, source: Any, overwrite: bool = True) -> None:
806
+ """
807
+ 将 source 对象的公开属性合并到 target 对象。
808
+ :param overwrite: 如果 target 已存在该属性,是否覆盖
809
+ """
810
+ source_dict = ObjectUtils.to_dict(source, exclude_private=True)
811
+ for k, v in source_dict.items():
812
+ if overwrite or not hasattr(target, k):
813
+ setattr(target, k, v)
814
+