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 function docstrings in the standard Sphinx format . That is, if you already have documentation, you do not need to do anything else to use PyFence!
For example, take the following class:
classRationalFormatter(object):defformat(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() defdisplay(self, number): print(str(number) + ' = ' + self.format(number))
The format method represents a fraction number using the float.as_integer_ratio ()
from formatter import RationalFormatter f = RationalFormatter() f.display(1.25) 1.25 = 5/4
Does it seem to work? However, everything will break if you pass int , because int , unfortunately, does not contain .as_integer_ratio () .
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'f.display(
However, when using PyFence, such a 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 and return types that occur in functions / methods.
You can also import the pyfence module in the project itself, in which case you do not have to use a separate fence utility .
Of course, it is worth using fence only during development, and not in production, since due to checks, a drop in performance is possible.
I will be very grateful to any feedback and pull requests !