Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mypy catch AttributeError

have been using the following code

import yaml
try:
    filterwarnings(yaml.YAMLLoadWarning)
except AttributeError:
    pass

But when I tried to run mypy today I got "module has no attribute YAMLLoadWarning". Which is true on some versions of python. Is there a better way to write this?

EDIT:

To be a little clearer, I know how to ignore the error (and catch the exception related to the python 3.6 version of pyyaml not including that exception). My question is more about working with the parser. Consider these examples-

I know that if you have a function that returns a more specific type

def bad(a: Optional[int]) -> int:
    return a  # Incompatible return value type (got "Optional[int]", expected "int")

You can use a branch to force only the correct type to be returned, and the parser notices

def good(a: Optional[int]) -> int:
    if a:
        return a
    return 0

So in situations where you handle error situations using a try/catch statement, is there a way to construct this so that the parser realizes that the attribute error is handled?

def exception_branch(a: Optional[str])-> list:
    try:
        return a.split()  # Item "None" of "Optional[str]" has no attribute "split"
    except:
        return []
like image 555
Paul Becotte Avatar asked Nov 16 '22 06:11

Paul Becotte


1 Answers

So in situations where you handle error situations using a try/catch statement, is there a way to construct this so that the parser realizes that the attribute error is handled?

No, there is not, I'm afraid. The problem is that catch AttributeError does not indicate where from the exception comes. So if you had

try:
    print(foo.barr)
    return a.split()
except AttributeError:
    return []

The typechecker can ignore the fact that a can be None, but it would have to ignore also the fact that you misspelled bar and there is no barr attribute in the object foo. See also here.

like image 53
volferine Avatar answered Jan 03 '23 02:01

volferine