Repository: mahmoud/boltons

Issue:
`boltons.funcutils.wraps` breaks with Python 3 function annotations
Tested with `boltons==17.1.0`

Repro: Executing the following script fails
```python
from boltons.funcutils import wraps
from typing import Optional

def wrap_it(f):
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        f(*args, **kwargs)
    return wrapper

@wrap_it
def foo(x: Optional[int]) -> Optional[int]:
    return x
```

Results in
```bash
rwilliams at rwilliams-mbp114 in ~/src/oss/boltons (master●) (venv)
$ python ../../test_wraps_with_annotations.py
Traceback (most recent call last):
  File "../../test_wraps_with_annotations.py", line 11, in <module>
    def foo(x: Optional[int]) -> Optional[int]:
  File "../../test_wraps_with_annotations.py", line 5, in wrap_it
    @wraps(f)
  File "/Users/rwilliams/src/oss/boltons/boltons/funcutils.py", line 307, in wrapper_wrapper
    fully_wrapped = fb.get_func(execdict, with_dict=update_dict)
  File "/Users/rwilliams/src/oss/boltons/boltons/funcutils.py", line 526, in get_func
    self._compile(src, execdict)
  File "/Users/rwilliams/src/oss/boltons/boltons/funcutils.py", line 590, in _compile
    exec(code, execdict)
  File "<boltons.funcutils.FunctionBuilder-0>", line 1, in <module>
NameError: name 'Union' is not defined
```

Discussion:

Patch:
diff --git a/boltons/funcutils.py b/boltons/funcutils.py
index 1a34373..17ab6d5 100644
--- a/boltons/funcutils.py
+++ b/boltons/funcutils.py
@@ -474,6 +474,7 @@ class FunctionBuilder(object):
                  'module': lambda: None,
                  'body': lambda: 'pass',
                  'indent': lambda: 4,
+                 "annotations": dict,
                  'filename': lambda: 'boltons.funcutils.FunctionBuilder'}
 
     _defaults.update(_argspec_defaults)
@@ -495,7 +496,12 @@ class FunctionBuilder(object):
     # def get_argspec(self):  # TODO
 
     if _IS_PY2:
-        def get_sig_str(self):
+        def get_sig_str(self, with_annotations=True):
+            """Return function signature as a string.
+
+            with_annotations is ignored on Python 2.  On Python 3 signature
+            will omit annotations if it is set to False.
+            """
             return inspect.formatargspec(self.args, self.varargs,
                                          self.varkw, [])
 
@@ -503,14 +509,23 @@ class FunctionBuilder(object):
             return inspect.formatargspec(self.args, self.varargs,
                                          self.varkw, [])[1:-1]
     else:
-        def get_sig_str(self):
+        def get_sig_str(self, with_annotations=True):
+            """Return function signature as a string.
+
+            with_annotations is ignored on Python 2.  On Python 3 signature
+            will omit annotations if it is set to False.
+            """
+            if with_annotations:
+                annotations = self.annotations
+            else:
+                annotations = {}
             return inspect.formatargspec(self.args,
                                          self.varargs,
                                          self.varkw,
                                          [],
                                          self.kwonlyargs,
                                          {},
-                                         self.annotations)
+                                         annotations)
 
         _KWONLY_MARKER = re.compile(r"""
         \*     # a star
@@ -552,6 +567,7 @@ class FunctionBuilder(object):
         kwargs = {'name': func.__name__,
                   'doc': func.__doc__,
                   'module': func.__module__,
+                  'annotations': getattr(func, "__annotations__", {}),
                   'dict': getattr(func, '__dict__', {})}
 
         kwargs.update(cls._argspec_to_dict(func))
@@ -590,7 +606,7 @@ class FunctionBuilder(object):
         body = _indent(self.body, ' ' * self.indent)
 
         name = self.name.replace('<', '_').replace('>', '_')  # lambdas
-        src = tmpl.format(name=name, sig_str=self.get_sig_str(),
+        src = tmpl.format(name=name, sig_str=self.get_sig_str(with_annotations=False),
                           doc=self.doc, body=body)
         self._compile(src, execdict)
         func = execdict[name]
@@ -600,6 +616,7 @@ class FunctionBuilder(object):
         func.__defaults__ = self.defaults
         if not _IS_PY2:
             func.__kwdefaults__ = self.kwonlydefaults
+            func.__annotations__ = self.annotations
 
         if with_dict:
             func.__dict__.update(self.dict)


Test patch:
diff --git a/tests/test_funcutils_fb_py3.py b/tests/test_funcutils_fb_py3.py
index 3effd7e..d0b4a79 100644
--- a/tests/test_funcutils_fb_py3.py
+++ b/tests/test_funcutils_fb_py3.py
@@ -1,5 +1,6 @@
 
 import inspect
+from collections import defaultdict
 
 import pytest
 
@@ -20,12 +21,13 @@ def pita_wrap(flag=False):
 def test_wraps_py3():
 
     @pita_wrap(flag=True)
-    def annotations(a: int, b: float=1) -> "tuple":
-        return a, b
+    def annotations(a: int, b: float=1, c: defaultdict=()) -> defaultdict:
+        return a, b, c
 
-    annotations(0) == (True, "annotations", (0, 1))
-    annotations.__annotations__ == {'a': int, 'b': float,
-                                    'return': 'tuple'}
+    assert annotations(0) == (True, "annotations", (0, 1, ()))
+    assert annotations.__annotations__ == {'a': int, 'b': float,
+                                           'c': defaultdict,
+                                           'return': defaultdict}
 
     @pita_wrap(flag=False)
     def kwonly_arg(a, *, b, c=2):
@@ -34,8 +36,8 @@ def test_wraps_py3():
     with pytest.raises(TypeError):
         kwonly_arg(0)
 
-    kwonly_arg(0, b=1) == (False, "kwonly_arg", (0, 1, 2))
-    kwonly_arg(0, b=1, c=3) == (False, "kwonly_arg", (0, 1, 3))
+    assert kwonly_arg(0, b=1) == (False, "kwonly_arg", (0, 1, 2))
+    assert kwonly_arg(0, b=1, c=3) == (False, "kwonly_arg", (0, 1, 3))
 
     @pita_wrap(flag=True)
     def kwonly_non_roundtrippable_repr(*, x=lambda y: y + 1):