Is there any way to detect AttributeErrors prior to runtime in Pycharm for child classes of Enum?
I have a simple child class of Enum:
class ContentEncoding(Enum):
UTF_8 = "utf-8"
BINARY = "binary"
If I try accessing some non-existant field, e.g.:
class ContentEncoding(Enum):
UTF_8 = "utf-8"
BINARY = "binary"
bar = ContentEncoding.foo
Pycharm doesn't show the usual "Unresolved attribute reference 'foo' for class ContentEncoding like I'd expect. The entire reason for using Enums in my case was to limit the values ContentEncoding could take. If there is no lint checks on this it seems kind of pointless to use an Enum in the first place.
Edit:
Adding the intended use-case for this Enum child class in hopes alternative solutions exist:
The intended use of this ContentEncoding class is to define the only valid encodings for some other encoder method.
For example, lets say this encoder method is as follows:
def encode(obj, encoding: str):
return black_box_encoder(obj, encoding)
where the only valid encoding str are "utf-8" or "binary". All other str would result in a runtime error.
So assume this ContentEncoding class and encode method are in some package called mypackage and I have a user who imports this package and wants to encode something.
import mypackage
obj = "foo"
bar = mypackage.encode(obj, mypackage.ContentEncoding.UTF_8.value)
Rather than making the user manually type "utf-8" and be prone to typos like "UTF-8", "Utf-8", etc. I wanted to have an enum (or some other object) than can be used to predefine the only valid values for the 2nd arg of encode.
I guess it would be better to type hint to ContentEncoding rather than str and do the value extraction within the encode method. e.g.
def encode(obj, encoding: ContentEncoding):
return black_box_encoder(obj, encoding.value)
import mypackage
obj = "foo"
bar = mypackage.encode(obj, mypackage.ContentEncoding.UTF_8)
Regardless, I'm still not seeing a way to get a lint/error check for an appropriate encoding string prior to runtime. If an alternative solution exists, please link me to something I can read up on.
To be clear, I want someway of having Pycharm (or other lint checker) to warn the user they have used an incorrect arg (prior to runtime) if they did something like this:
import mypackage
obj = "foo"
bar = mypackage.encode(obj, mypackage.ContentEncoding.utf_8)