使 pyro4 代理可索引

make pyro4 proxy indexable

我正在尝试使 pyro4 代理可索引。为了测试这一点,我从 http://pythonhosted.org/Pyro4/intro.html#simple-example 中获取了问候语示例并对其进行了修改:

服务器:

import Pyro4

class Test(object):

    def __getitem__(self, index):
        return index

test = Test()
print test[1]
print test[100]


daemon = Pyro4.Daemon()
uri = daemon.register(test)


print("Ready. Object uri =", uri)
daemon.requestLoop()

客户:

import Pyro4

uri = input("What is the Pyro uri of the object? ").strip()

test = Pyro4.Proxy(uri)
print test.__getitem__(1)
print test.__getitem__(100)

print test[1]
print test[100]

[] 表示法适用于服务器,但不适用于客户端代理。我得到:

TypeError: 'Proxy' object does not support indexing

但直接调用 __getitem__ 确实有效。

我自己刚刚 运行 喜欢这个。

从我看到的 the source code 来看,Pyro4 不代理索引符号使用的 Python 隐式 __getitem__ 调用。它做代理 __getattr__,这就是为什么直接调用 __getitem__ 方法有效。

不过,您可以做的是(在客户端)创建 Pyro 代理 (!) 的代理,实现 __getitem__ 并让所有其他方法调用失败:

class TestProxy(object):
    def __init__(self, pyroTest):
        self.pyroTest = pyroTest

    def __getattr__(self, name):
        return getattr(self.pyroTest, name)

    def __getitem__(self, item):
        return self.pyroTest.__getitem__(item)

然后您可以在 TestProxy 对象上使用索引符号,以及以正常的 Pyro 方式调用方法。

(免责声明:这个简单的解决方案可能无法涵盖各种 Pythonic 边界情况!)

这可能值得 Pyro 的增强请求。

虽然这可能会被添加到 Pyro 代理中,但它实际上会促进潜在的糟糕执行代码。 索引一个对象通常是因为该对象是某种集合并且您可能正在迭代它。在 Pyro 代理上执行此操作将导致糟糕的性能,因为每次索引查找都是远程调用。 使用一个远程调用一次简单地获取要遍历的集合,然后像往常一样遍历生成的本地对象,通常会更快、更有效。 YMMV,当然要视情况而定。