Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting str to Literal["a", "b", ... #11363

Closed
ghost opened this issue Oct 19, 2021 · 1 comment
Closed

Converting str to Literal["a", "b", ... #11363

ghost opened this issue Oct 19, 2021 · 1 comment
Labels

Comments

@ghost
Copy link

ghost commented Oct 19, 2021

Let's say we have a function that takes multiple Literal arguments.

def takes_a_literal(foo: Literal["a", "b"]) -> None:
    print(foo)

And we call that function, from a function that takes a string.

def does_something(foo: str) -> None:
    takes_a_literal(foo)

Obviously, this will fail because foo can be anything. But what if we want to be assertive?

assert foo in ["a", "b], reveal_type(foo) is still str.

I can't even cast it: cast(Literal["a", "b"], foo) -- reveal_type(foo) still says str.

The only thing I've found that works is this:

literal_foo: Literal["a", "b"]
if foo == "a":
    literal_foo = "a"
elif foo == "b":
    literal_foo = "b"

Then passing literal_foo. This gets quite wordy with more than a couple of Literals.

Is there another way to do this?

@ghost ghost added the question label Oct 19, 2021
@JelleZijlstra
Copy link
Member

This is a duplicate of #10977.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant