1

Consider the code below. This fails to run properly with mypyc because Proxy does not have a __dict__ attribute at runtime.

So the questions are:

  1. Is there any documentation regarding the subset of the language that mypyc supports? I can't seem to find much out there.

  2. Is there another a way to do what I want which is to capture and later process how an object is accessed/manipulated.

Thanks!

import typing


class Proxy:
    def __init__(self) -> None:
        self.__dict__['__ops'] = []

    def __setattr__(self, name: str, value: typing.Any) -> None:
        self.__dict__['__ops'].append(('SetAttr', name, value))

    def __getattr__(self, name: str) -> "Proxy":
        self.__dict__['__ops'].append(('GetAttr', name))
        return self

    def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
        self.__dict__['__ops'].append(('SetItem', key, value))

    def __getitem__(self, key: typing.Any) -> "Proxy":
        self.__dict__['__ops'].append(('GetItem', key))
        return self

    def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
        self.__dict__['__ops'].append(('Call', args, kwargs))

p = Proxy()
Sohail
  • 3,020
  • 1
  • 25
  • 23

1 Answers1

1

Defining the list as a normal member should have the same effect as defining it via __dict__. I have no specific knowledge about mypyc, but this should work in any compliant Python 3 implementation.

class Proxy:
    def __init__(self) -> None:
        self.__ops = []

    def __setattr__(self, name: str, value: typing.Any) -> None:
        self.__ops.append(('SetAttr', name, value))

    def __getattr__(self, name: str) -> "Proxy":
        self.__ops.append(('GetAttr', name))
        return self

    def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
        self.__ops.append(('SetItem', key, value))

    def __getitem__(self, key: typing.Any) -> "Proxy":
        self.__ops.append(('GetItem', key))
        return self

    def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
        self.__ops.append(('Call', args, kwargs))
Xtrem532
  • 756
  • 8
  • 19
  • True, this does work, however the problem is that mypyc does not appear to support overriding setattr/getattr and friends. My question was not well asked... – Sohail Mar 13 '21 at 04:10