Search code examples
python

UserWarning: no type annotations present -- not typechecking __main__.my_func warn('no type annotations present -- not typechecking {}'.format(functio


Why is typeguard not typechecking a function?

The function works without the @typechecked decorator. Running with it gives a warning, stating no type checking is performed.

from typeguard import typechecked


@typechecked
def my_func(x, y):
    z = x + y
    return z


a = my_func(1, 2)
print(a)
(venv) me@ubuntu-pcs:~/PycharmProjects/project$ python3 foo/bar.py 
/home/me/miniconda3/envs/venv/lib/python3.9/site-packages/typeguard/__init__.py:1016: UserWarning: no type annotations present -- not typechecking __main__.my_func
  warn('no type annotations present -- not typechecking {}'.format(function_name(func)))
1 2
None

Solution

  • By design, typeguard will ignore the contents of any function objects that don't have type annotations.

    To ensure typechecking, you must include type hints on the function's defined arguments.

    from typeguard import typechecked
    
    
    @typechecked
    def my_func(x: int, y: int):
        z = x + y
        return z
    
    
    a = my_func(1, 2)
    print(a)
    
    (venv) me@ubuntu-pcs:~/PycharmProjects/project$ python3 foo/bar.py 
    3