How to specify argument type in a dynamically typed language, i.e. Python?

后端 未结 5 1673
甜味超标
甜味超标 2021-01-23 13:11

Is there any such equivalent of Java

String myMethod (MyClass argument) {...}

in Python?

Thank you, Tomas

5条回答
  •  自闭症患者
    2021-01-23 13:24

    I just want to say that I'm in full agreement that type checking is evil. But python is also incredibly flexible and I'm in the mood to be evil. This code will take effect at runtime and not compile time. You could do something similar for return type. Something like this could be useful for debugging and, because it's a decorator, it's easy enough to remove.

    For it to be useful for debugging you would have to have a situation where two types had all the same attributes that were getting accessed but with different semantics. So that's a pretty limited case. Other than that, you're about to get a typerror anyways when this code runs. The good news is that this is almost never a problem. I really don't know why people from statically typed languages make such a big deal over it.

    def types(*args, **kwargs):
        arg_types = args
        kwarg_types = kwargs
        def decorator(f):
            def func(*args, **kwargs):
                for arg, arg_type in zip(args, arg_types):
                    if not isinstance(arg, arg_type):
                        raise TypeError("Wrong type suckah")
                for kw, arg in kwargs.items():
                    if not isinstance(arg, kwarg_types[kw]):
                        raise TypeError("this is a bad error message")
                return f(*args, **kwargs)
            return func
        return decorator
    
    @types(int, str, bool, flag=bool)
    def demo(i, strng, flag=False):
        print i, strng, flag
    
    demo(1, "foo", True)
    
    try:
        demo("foo", "bar", flag="foobar")
    except TypeError:
        print "busted on posargs"
    
    try:
        demo(1, "foo", flag=2)
    except TypeError:
        print "busted on keyargs"
    
    try:
        demo(1, "foo", 3)
    except TypeError:
        print "no use sneaking it through"
    

提交回复
热议问题