简体   繁体   中英

Is there a way for mypyc to compile a proxy object?

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()

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM