Typing in python

Unfortunately, I don't know how much the title corresponds to the problem described below, if it can be considered a problem at all.

For example, there is a function:

def handler(service , command, *args, **kwargs):
    if command not in ['create', 'update', 'delete', 'list']:
        ...
    service.do_smth()

For example, I know that a service object is an instance of a particular class. When trying to call a class method, I must either blindly call the method, or go into the module with classes and look at the names of the methods. The arguments are even worse. If in the case of methods, if you start writing them ide \ editor will tell you what to write next, then in the case of arguments, this does not happen.

More recently, you can explicitly specify the type by writing service: ServiceType. This really solves the problem.

Similar situation

[ print(x.attr) for x in api.get_smth() ]

I have to guess which attribute I want to output, because the type of object x is not known.

The question is the following: I believe that this is a normal phenomenon, and the fee for dynamic typing. The only question is how to deal with it? And how to write code.

Author: TorSen, 2018-06-13

2 answers

A good IDE (free PyCharm) solves these problems. Yes, it is necessary to specify the type of function parameters, well, it is easier to program (especially returning to the code in a year or two). The IDE itself will try to calculate the return type from some get_smth (), but you can also specify it explicitly, which is also useful for maintenance and documentation.

 1
Author: Alex Titov, 2018-06-14 16:31:53

You can determine the type of the object using type() or check that the object is of the desired type using isinstance()

def sum_two_ints(a, b):
    if isinstance(a, int) and isinstance(b, int):
        return a+b
    else:
        raise TypeError
 0
Author: pinguin, 2018-06-13 08:57:28