Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can mypy ignore a single line in a source file?

Tags:

python

types

mypy

I'm using mypy in my python project for type checking. I'm also using PyYAML for reading and writing the project configuration files. Unfortunately, when using the recommended import mechanism from the PyYAML documentation this generates a spurious error in a try/except clause that attempts to import native libraries:

from yaml import load, dump try:     from yaml import CLoader as Loader, CDumper as Dumper except ImportError:     from yaml import Loader, Dumper 

On my system CLoader and CDumper aren't present, which results in the errors error: Module 'yaml' has no attribute 'CLoader' and error: Module 'yaml' has no attribute 'CDumper'.

Is there a way to have mypy ignore errors on this line? I was hoping that I could do something like this to have mypy skip that line:

from yaml import load, dump try:     from yaml import CLoader as Loader, CDumper as Dumper  # nomypy except ImportError:     from yaml import Loader, Dumper 
like image 717
Pridkett Avatar asked Mar 11 '18 12:03

Pridkett


People also ask

How do you ignore a line in MYPY?

You can use the form # type: ignore[<code>] to only ignore specific errors on the line.

What is MYPY Python?

“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” A little background on the Mypy project.


1 Answers

You can ignore type errors with # type: ignore as of version 0.2 (see issue #500, Ignore specific lines):

PEP 484 uses # type: ignore for ignoring type errors on particular lines ...

Also, using # type: ignore close to the top of a file [skips] checking that file altogether.

Source: mypy#500. See also the mypy documentation.

like image 100
Salem Avatar answered Sep 22 '22 21:09

Salem