Ignoring mypy attr-defined with triple quotes

Question:

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?

Asked By: a.t.

||

Answers:

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.

Answered By: user2357112
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.