Pylint: Class 'message' has no member 'startswith'

For some reason, pylint 1.6.4 (astroid 1.4.9) doesn't like it:

 try: some_package.their_function() except Exception as ex: if ex.message.startswith(...): ... 

He complains:

 error (E1101, no-member, feed_sentiment) Class 'message' has no 'startswith' member 

I find this amazing because:

 >>> type(Exception("foo").message) <type 'str'> >>> Exception("foo").message.startswith <built-in method startswith of str object at 0x10520d360> 

I think this is a bug in pylint .

However, am I doing something wrong? What is the "pythonic" way here?

PS. Yes, I know that the correct way is to define my own subclass of exceptions, but I cannot control some_package .

SFC. Yes, I know that I can annotate the code with pylint: disable=no-member .

+5
source share
2 answers

The pythonic paths would need to convert ex to str explicitly, because it also converts the message to a string:

 try: some_package.their_function() except Exception as ex: if str(ex).startswith(...): # or "if something in str(ex)": 

The problem with Exception.message is that it cannot be str :

 >>> try: ... raise ValueError(1.2) ... except Exception as ex: ... print ex ... print type(ex.message) ... print repr(str(ex)) # force it to be a string ... print hasattr(ex.message, 'startswith') ValueError(1.2,) <type 'float'> '1.2' False 

Good style and it is highly advisable to use str as a message, but this is by no means guaranteed!

0
source

This is really a mistake in the astroid internal library - a pylint , used to build abstract syntax trees and output values.

 import astroid node = astroid.builder.parse(""" ex = Exception() msg = ex.message """) print list(node.locals['msg'][0].infer()) 

The output from this piece of code is:

 [<ClassDef(message) l.0 [exceptions] at 0x34aadd0>, <ClassDef(message) l.0 [exceptions] at 0x3482cb0>] 

Output means that the message attribute in the exception instance is defined as the definition of the user class, and not the string instance.

Thanks for submitting an error!

+1
source

Source: https://habr.com/ru/post/1263686/


All Articles