2

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?

6
  • 1
    Why do you want the type annotation to have anything to do with SomeClass? It sounds like it should just be str. Commented Oct 26, 2019 at 1:20
  • 1
    If you want to ensure that the input is one of SomeClass's class variables, well, "one of SomeClass's class variables" isn't a type. Commented Oct 26, 2019 at 1:22
  • @user2357112 - I want the actual value passed to be one of the SomeClass's defined values. I know type-hints aren't meant to enforce values, but can they not be used to enforce type? (in this case, SOME_STRINGs are "members" of SomeClass) Commented Oct 26, 2019 at 1:22
  • Your notion of "membership" is not how the type system works. Commented Oct 26, 2019 at 1:26
  • @user2357112 - fair enough. Thanks for answering. Commented Oct 26, 2019 at 1:26

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.