_utilities.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from __future__ import annotations
  2. import collections.abc as c
  3. import inspect
  4. import typing as t
  5. from weakref import ref
  6. from weakref import WeakMethod
  7. T = t.TypeVar("T")
  8. class Symbol:
  9. """A constant symbol, nicer than ``object()``. Repeated calls return the
  10. same instance.
  11. >>> Symbol('foo') is Symbol('foo')
  12. True
  13. >>> Symbol('foo')
  14. foo
  15. """
  16. symbols: t.ClassVar[dict[str, Symbol]] = {}
  17. def __new__(cls, name: str) -> Symbol:
  18. if name in cls.symbols:
  19. return cls.symbols[name]
  20. obj = super().__new__(cls)
  21. cls.symbols[name] = obj
  22. return obj
  23. def __init__(self, name: str) -> None:
  24. self.name = name
  25. def __repr__(self) -> str:
  26. return self.name
  27. def __getnewargs__(self) -> tuple[t.Any, ...]:
  28. return (self.name,)
  29. def make_id(obj: object) -> c.Hashable:
  30. """Get a stable identifier for a receiver or sender, to be used as a dict
  31. key or in a set.
  32. """
  33. if inspect.ismethod(obj):
  34. # The id of a bound method is not stable, but the id of the unbound
  35. # function and instance are.
  36. return id(obj.__func__), id(obj.__self__)
  37. if isinstance(obj, (str, int)):
  38. # Instances with the same value always compare equal and have the same
  39. # hash, even if the id may change.
  40. return obj
  41. # Assume other types are not hashable but will always be the same instance.
  42. return id(obj)
  43. def make_ref(obj: T, callback: c.Callable[[ref[T]], None] | None = None) -> ref[T]:
  44. if inspect.ismethod(obj):
  45. return WeakMethod(obj, callback) # type: ignore[arg-type, return-value]
  46. return ref(obj, callback)