codekingpro/portable-devtools
114k
1from __future__ import annotations2 3import collections.abc as c4import inspect5import typing as t6from weakref import ref7from weakref import WeakMethod8 9T = t.TypeVar("T")10 11 12class Symbol:13 """A constant symbol, nicer than ``object()``. Repeated calls return the14 same instance.15 16 >>> Symbol('foo') is Symbol('foo')17 True18 >>> Symbol('foo')19 foo20 """21 22 symbols: t.ClassVar[dict[str, Symbol]] = {}23 24 def __new__(cls, name: str) -> Symbol:25 if name in cls.symbols:26 return cls.symbols[name]27 28 obj = super().__new__(cls)29 cls.symbols[name] = obj30 return obj31 32 def __init__(self, name: str) -> None:33 self.name = name34 35 def __repr__(self) -> str:36 return self.name37 38 def __getnewargs__(self) -> tuple[t.Any, ...]:39 return (self.name,)40 41 42def make_id(obj: object) -> c.Hashable:43 """Get a stable identifier for a receiver or sender, to be used as a dict44 key or in a set.45 """46 if inspect.ismethod(obj):47 # The id of a bound method is not stable, but the id of the unbound48 # function and instance are.49 return id(obj.__func__), id(obj.__self__)50 51 if isinstance(obj, (str, int)):52 # Instances with the same value always compare equal and have the same53 # hash, even if the id may change.54 return obj55 56 # Assume other types are not hashable but will always be the same instance.57 return id(obj)58 59 60def make_ref(obj: T, callback: c.Callable[[ref[T]], None] | None = None) -> ref[T]:61 if inspect.ismethod(obj):62 return WeakMethod(obj, callback) # type: ignore[arg-type, return-value]63 64 return ref(obj, callback)65 