core: Generalize __setitem__ and __getitem__ #487

Open
opened 2024-08-09 17:23:32 +08:00 by lyken · 0 comments
Collaborator

A more advanced version of #460 and #482.

Technically, Python allows dunder methods like __setitem__ and __getitem__ to be overriden in user-defined classes. For a dumb example:

T = TypeVar("T")

class MyReversedList(Generic[T]):
  def __init__(self, value: list[T]) -> None:
    self.value = value

  def __getitem__(self, key: int) -> T:
    return self.value[key - len(self.value) - 1]

  def __setitem__(self, key: int, value: T) -> None:
    self.value[key - len(self.value) - 1] = value

Right now, nac3core has other magic functions like __add__ and friends to deal with {u,}int{32,64} and float binary operations, etc.

Builtin item assignment __setitem__ and item lookups __getitem__ could also be implemented like this - as top-level builtin functions attributed to a primitive class (including lists, ndarrays, maybe a bit awkward for TypeEnum::Tuples since they are not TObj and would require special checks in the type system).

An extension to this is to add a feature to allow users to define their own __setitem__ and __getitem__ in their own classes.

This is considered low priority.

A more advanced version of https://git.m-labs.hk/M-Labs/nac3/issues/460 and https://git.m-labs.hk/M-Labs/nac3/issues/482. Technically, Python allows dunder methods like `__setitem__` and `__getitem__` to be overriden in user-defined classes. For a dumb example: ```python T = TypeVar("T") class MyReversedList(Generic[T]): def __init__(self, value: list[T]) -> None: self.value = value def __getitem__(self, key: int) -> T: return self.value[key - len(self.value) - 1] def __setitem__(self, key: int, value: T) -> None: self.value[key - len(self.value) - 1] = value ``` Right now, `nac3core` has other magic functions like `__add__` and friends to deal with `{u,}int{32,64}` and `float` binary operations, etc. Builtin item assignment `__setitem__` and item lookups `__getitem__` could also be implemented like this - as top-level builtin functions attributed to a primitive class (including `list`s, `ndarray`s, maybe a bit awkward for `TypeEnum::Tuple`s since they are not `TObj` and would require special checks in the type system). An extension to this is to add a feature to allow users to define their own `__setitem__` and `__getitem__` in their own classes. This is considered low priority.
lyken added the
low-priority
label 2024-08-09 17:23:46 +08:00
Sign in to join this conversation.
No Milestone
No Assignees
1 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: M-Labs/nac3#487
No description provided.