Ignoring mypy attr-defined with triple quotes

The following code:

# type: ignore[attr-defined]
timeit.template = """ # type: ignore[attr-defined]
def inner(_it, _timer{init}):
    {setup}
    _t0 = _timer()
    for _i in _it:
        retval = {stmt}
    _t1 = _timer()
    return _t1 - _t0, retval
"""  # type: ignore[attr-defined]
# type: ignore[attr-defined]

Yields error:

src/snncompare/Experiment_runner.py:45: error: Module has no attribute "template"  [attr-defined]
Found 1 error in 1 file (checked 97 source files)

How can I ensure mypy ignores only this one instance of the creation of the attribute?

>Solution :

You can use implicit line continuation with parentheses, so you can put a comment on the first line of the assignment:

timeit.template = ( # type: ignore[attr-defined]
"""
def inner(_it, _timer{init}):
    {setup}
    _t0 = _timer()
    for _i in _it:
        retval = {stmt}
    _t1 = _timer()
    return _t1 - _t0, retval
""")

If you want something less prone to getting messed up by autoformatters, you can introduce an intermediate variable:

template = """
def inner(_it, _timer{init}):
    {setup}
    _t0 = _timer()
    for _i in _it:
        retval = {stmt}
    _t1 = _timer()
    return _t1 - _t0, retval
"""

timeit.template = template # type: ignore[attr-defined]

That said, your use case is a bad idea. It will mess with all uses of timeit anywhere in the process, including library code you had no idea needed timeit. If you want to know what an expression evaluates to, just evaluate it once, outside of the timeit call.

Leave a Reply