zerohedge
zerohedge

Reputation: 3765

Python: How to type-hint a class variable?

Yes, I'm aware of the Enum class but I'm not interested in using it.

This is my Class enum:

class SomeClass:
    SOME_STRING = "regular"
    SOME_STRING2 = "important"
    SOME_STRING3 = "accounts"
    SOME_STRING4 = "special"

This is my type-hinted function:

def do_something(*, queue_name: SomeClass):
    #....

And when I call it like this:

purge_queue(queue_name=SomeClass.SOME_STRING)

I get a warning:

Argument of type 'Literal['regular']' cannot be assigned to parameter 'queue_name' of type 'SomeClass' 'str' is incompatible with 'SomeClass'

What am I doing wrong?

Upvotes: 2

Views: 1539

Answers (1)

user2357112
user2357112

Reputation: 281757

A type hint of SomeClass means that values should be instances of SomeClass, not class variables of SomeClass. "One of SomeClass's class variables" isn't a type, and there is no annotation you can use with that meaning.

The stdlib solution for this kind of thing is enum.Enum, but you've rejected that. In that case, the next best thing is the typing.Literal type, introduced in Python 3.8. With that, you can write things like

SomeClassValue = typing.Literal['regular', 'important', 'accounts', 'special']

def do_something(*, queue_name: SomeClassValue):
    ...

You cannot somehow pull the type parameters from the class variables of SomeClass; it might run, but it won't type-check. This means you'll have to have a lot of error-prone code duplication if you go down this route. (Also, you'll probably need to put Final annotations on your class variables, to indicate they're not supposed to be reassigned.)

Upvotes: 4

Related Questions