Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading