简体   繁体   English

在python中将Callable键入特定的方法

[英]Typing Callable in python to specific methods

I am trying to be very strict with my typing, and I encounter an issue when I want to type a Callable to only a few very specific methods! 我试图对输入进行非常严格的操作,但是我只想用几种非常特定的方法来键入Callable时遇到一个问题!

I have a class: 我有一堂课:

class Complex:

    def __add__(self, other):
        return Complex()

    def __sub__(self, other):
        return Complex()

    def __div__(self, other):
        return Complex()

In another file I want to write a method that takes in a Callable, but the argument to the method can ONLY be either the add function or the sub function. 在另一个文件中,我想编写一个接受Callable的方法,但是该方法的参数只能是add函数或sub函数。 That means I want the linter to throw an error if I try to pass in div as a function to test_add_sub() 这意味着如果我尝试将div作为函数传递给test_add_sub(),我希望linter引发错误。

The code below doesn't seem to work :( The linter nor the compiler complains when I pass in the div function to test_add_sub! Nor can I write Complex.complex_func(). 下面的代码似乎不起作用:(当我将div函数传递给test_add_sub时,lint或编译器都会抱怨!也无法编写Complex.complex_func()。

    add_sub_type = Complex.__add__ or Complex.__sub__
    add_sub_type2 = Callable[[Complex.__add__ or Complex.__sub__], None]


    def test_add_sub(complex_func: add_sub_type) -> None:
        print(complex_func)
        Complex.complex_func() <-- 'Class Complex has no complex_func member'

Thank you all very much in advance. 预先非常感谢大家。

typing can't do that. typing不能做到这一点。 The static pseudo-type system doesn't allow you to define a type with an arbitrary set of members. 静态伪类型系统不允许您定义具有任意成员集的类型。 (Also, Complex.complex_func() isn't how you'd call complex_func anyway.) (此外, Complex.complex_func()也不是您如何调用complex_func的方法。)

If you really, really want a static, type-based check for this, you could use an enum instead of the methods: 如果您确实希望对此进行基于类型的静态检查,则可以使用枚举代替方法:

class ComplexAddSub(enum.Enum):
    add = Complex.__add__
    sub = Complex.__sub__

    def __call__(self, left: Complex, right: Complex):
        return self.value(left, right)

def whatever(func: ComplexAddSub):
    func(Complex(), Complex())

whatever(ComplexAddSub.add)

Runtime detection 运行时检测

def test_add_sub(complex_func):
    tester = {Complex.__addr__: False, Complex.__sub__: False}
    if (tester.get(complex_func, True)):
        raise RuntimeError('Invalid argument!')

    #complex_func(some_complex_object, another_complex_object)

Read more about Instance methods here . 在此处阅读有关实例方法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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