Do you have too many statements (in Python)?

Recently, I have added asserts almost every single function that I do, to check each input as an unscrupulous substitute for type checking or to prevent accidental input of incorrect data during development. For instance,

 def register_symbol(self, symbol, func, keypress=None): assert(isinstance(symbol, basestring)) assert(len(symbol) == 1) assert(callable(func)) assert(keypress is None or type(keypress) is int) self.symbols_map[symbol] = (func, keypress) return 

However, I worry that this runs counter to the idea of ​​duck printing, and that I may be too mistaken or squeeze myself unnecessarily. Can you have too many statements? When will you stop?

+6
source share
3 answers

I only use assert if they provide much better diagnostics than the error messages I would otherwise receive. Your third statement

 assert(callable(func)) 

can be an example for such a statement - if func not callable, you will receive an error message in a completely different line of code than in the case of the actual error, and it may be unclear -callable object in self.symbols_map . I write "maybe" because it depends on the rest of your code - if this is the only place where self.symbols_map updated, the statement may also be unnecessary.

The first and last statement, of course, contradict the idea of ​​duck input , and the second is redundant. If symbol not a string of length 1, it is possible that self.symbols_map[symbol] will raise KeyError , so there is no need for statements.

The last statement is also incorrect - type(keypress) cannot be None , and type checks must be performed using isinstance() . There may be very specialized applications where you cannot resolve subtypes, but checking should be done using type(x) is int instead of type(x) == int . The None check should be done using x is None , not type(x) is NoneType .

You should probably write a good set of unit tests - they will be much more useful than statements, and can make almost all of your statements redundant.

+7
source

Code delays are not as useful as unittests. Make more of the last, less than the first.

+3
source

Keep in mind that assert statements are removed when Python generates optimized bytecode! Since this is the case in most production environments, assert statements cannot be used to validate input. In fact, I came to the conclusion that I cannot use them for anything unless I can rely on their execution. Therefore, if I need to check some condition, instead I use "if ... raise ...", and if I just want to check my code, I write unittests.

+2
source

Source: https://habr.com/ru/post/910276/


All Articles