| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | from typing import Any, Dict, Tuple, Type, TypeVar |
| 8 | |
| 9 | T = TypeVar("T") |
| 10 | |
| 11 | |
| 12 | class SlotsMeta(type): |
| 13 | def __new__( |
| 14 | cls: Type[T], name: str, bases: Tuple[type, ...], ns: Dict[str, Any] |
| 15 | ) -> T: |
| 16 | # caller may have already provided slots, in which case just retain them and keep going |
| 17 | slots: Tuple[str, ...] = ns.get("__slots__", ()) |
| 18 | |
| 19 | # add fields with type annotations to slots |
| 20 | annotations: Dict[str, Any] = ns.get("__annotations__", {}) |
| 21 | members = tuple(member for member in annotations.keys() if member not in slots) |
| 22 | |
| 23 | # assign slots |
| 24 | ns["__slots__"] = slots + tuple(members) |
| 25 | return super().__new__(cls, name, bases, ns) # type: ignore |
| 26 | |
| 27 | |
| 28 | class Slots(metaclass=SlotsMeta): |
| 29 | pass |