[code-quality] Python skeletons: type hinting for third-party libraries

Andrey Vlasovskikh andrey.vlasovskikh at gmail.com
Mon Nov 11 14:00:30 CET 2013


Florian,

>>> You could also put asserts (and expressions which assert the presence of
>>> certain attributes) in function bodies.
>> 
>> Nice idea—that seems to give more flexibility, but (probably) makes it harder to implement.
>> 
>> I would love to write:
>> 
>>     assert hasattr(file_like, 'read') and hasattr(file_like, 'write')
>> 
>> Or maybe:
>> 
>>     assert file_like.read and file_like.write
> 
> I actually expect something like this:
> 
>    file_like.read(0)
>    file_like.write("")
> 
> No assert statements, just straight-line code that is supposed to be easy to analyze.  If the analyzer cannot use the information that file_like must have a callable read attribute that takes an integer argument, it could still use the information that a "read" attribute must be present.


Currently Python skeletons already include return values that are easy to parse. Static analyzers that do not support current type conventions of Python skeletons can already benefit from skeletons, because most of them can infer return types of functions. Note that sometimes it is hard to construct a simple return value of the given type.

How would you annotate a function that takes a string and does something complex with it?

   def f(s):
      s.lower()

would be not enough since 'f' may require a parameter with more methods than just 'lower'. Also it would be confusing from the user experience perspective. Compare these error messages from a static analysis tool:

   First argument of 'f' must be of type 'str'

   First argument of 'f' must have 'lower', 'strip' and '__getitem__' defined on it

It seems that the most simple way of documenting functions is putting types of their parameters and return values.

-- 
Andrey Vlasovskikh
Senior Software Developer
JetBrains
http://www.jetbrains.com/
"Develop with pleasure!"



More information about the code-quality mailing list