📜 ⬆️ ⬇️

PyFence: Type Verification for Python



PyFence is a self-made utility library that allows you to monitor type matching while debugging your project. PyFence takes type information from docstring functions in standard Sphinx format . That is, if you already have the documentation, you don’t need to do anything else to use PyFence!

For example, take the following class:

')
class RationalFormatter (object): def format(self, number): """ Stringifies a number to numerator/denominator format Example:: >>> print(RationalFormatter().format(1.25)) 5/4 :param number: input number :type number: float :raises : None :rtype : str """ return '%i/%i' % number.as_integer_ratio() def display(self, number): print(str(number) + ' = ' + self.format(number)) 


The format method represents a number as a fraction using the float.as_integer_ratio () method

We try:

 >>> from formatter import RationalFormatter >>> f = RationalFormatter() >>> f.display(1.25) 1.25 = 5/4 


It seems to work? However, everything will break if you pass an int , because unfortunately, .as_integer_ratio () does not contain an int .

 >>> f.display(5) Traceback (most recent call last): File "example.py", line 5, in <module> f.display(5) File "/home/eugeny/Work/pyfence/example_formatter.py", line 18, in display print(str(number) + ' = ' + self.format(number)) File "/home/eugeny/Work/pyfence/example_formatter.py", line 15, in format return '%i/%i' % number.as_integer_ratio() AttributeError: 'int' object has no attribute 'as_integer_ratio' 


However, when using PyFence, this problem could have been noticed much earlier:

 $ pip install pyfence ... $ fence example.py --fence:strict,stop 1.25 = 5/4 *** PyFence ERROR --------------------------- *** PyFence ERROR PyFence verification failed *** PyFence ERROR :: example_formatter.RationalFormatter.format(<example_formatter.RationalFormatter object at 0x7ff097a47d10>, 5) *** PyFence ERROR in example_formatter.py:2 *** PyFence ERROR number was 5 (int) instead of ['float'] *** PyFence ERROR Aborting 


In addition, PyFence can check the types of exceptions that occur in functions / methods and return types.
You can also import the pyfence module in the project itself, in this case you will not have to use a separate fence utility.
Of course, the use of the fence is only in the development, and not in the production, since due to the checks it is possible the performance to drop.

I will be very grateful to any feedback and pull request !

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


All Articles