AndreaCensi / contracts

PyContracts is a Python package that allows to declare constraints on function parameters and return values. Contracts can be specified using Python3 annotations, or inside a docstring. PyContracts supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts and an extension API.
http://andreacensi.github.io/contracts/
Other
398 stars 62 forks source link

Certain bad annotations result in AttributeError (fixed, patch included) #12

Closed asharp closed 11 years ago

asharp commented 11 years ago

Currently if you use the @contract decorator with a function that has something like """ :param myparam: something """ without specifying a :type myparam: you receive a traceback that looks like

File "[snip]/python2.6/site-packages/contracts/main.py", line 345, in remove_quotes if x.startswith('') and x.endswith('') and len(x) > 3: AttributeError: 'NoneType' object has no attribute 'startswith'

This is because on line 363, params[name].type is None, which is then passed into the remove_quotes function.

The following patch filters out malparsed params, thus stopping the error.

Patch follows:

@@ -356,6 +356,11 @@

     # These are the annotations
     params = annotations.params
+    #ignore non parsable params (TODO, perhaps warn?)
+    for name in params.keys():
+        if params[name].type is None:
+            del params[name]
+
     name2type = dict([(name, remove_quotes(params[name].type))
                        for name in params])
AndreaCensi commented 11 years ago

Thanks for reporting this.