0
0

Ray.remoteがついたメソッド内で親クラスを参照するとエラーになる

Posted at

コード

colab.ipynb
import ray
ray.init()

class A: 
    def add_5(self, a:int) -> int:
        return a + 5

class B(A):
    @ray.remote
    def add_5(self, *args, **kwargs) -> int:
        return super().meth(*args, **kwargs)

ray.get(B().add_5.remote(5))
#^^^^^^^^^^^^^^^^^^^^^^^^^^^
ray.shutdown()

エラー

.stderr
RayTaskError(TypeError): ray::meth():
  File "colab.ipynb", line 10, in meth
TypeError: super(type, obj): obj must be an instance or subtype of type

解決策

明示的にselfを渡す

colab.ipynb
# --snip--
b = B()
print(ray.get(b.add_5.remote(b, 5)))
# 10

原因

メソッドにray.remoteをつけると、そのメソッドはラッパー関数に置き換えられてしまいます。そのため、Pythonがself自動的に渡してくれなくなり、引数が不足します。今回の例では、引数が可変長引数だったため、selfの枠に5が入り、super(B, 5)となりエラーを吐いていました。
また、可変長引数を普通の引数に置き換えると、更にわかりやすいエラーが出ます。

code.py
import ray
ray.init() 

class Sample:
    @ray.remote
    def meth(self, some):pass

print(ray.get(meth.remote(5)))
#                         ^
ray.shutdown()
.stderr
TypeError: missing a required argument: 'some'
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0