-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
[red-knot] support fstring expressions #13511
[red-knot] support fstring expressions #13511
Conversation
0039716
to
8ec8dab
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh wow nice and thanks for explaining how mypy handles this.
|
3ee3fcb
to
05f15bd
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is great, thank you! I think there are still a couple things to address before landing.
I implemented the methods While doing so, I figured out a couple things: |
Ah! Very good point. I forgot about this -- |
It actually uses |
Current implementation (based on mypy behaviour): - evaluate any fstring with expressions as `builtin.str` - evaluate static fstrings (could be regular strings) as `Literal[..]` if it fits the max size or `LiteralString` (same as regular strings)
…sions Resolves f-strings made entirely of literals (bool, int, str) at compile time (not supported by mypy). Example: 'f"{True}"' -> 'True'
Implement the methods `Type::str` and `Type::repr` for some basic types and use it when infering the type of an f-string expression. Ensure we always infer sub-expressions in an f-string expression, even when we're done figuring out its type.
c9dfb96
to
04ed1b5
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is very close, thanks for sticking with it! Just a couple small comments yet.
Summary
Implement inference for
f-string
, contributes to #12701.First Implementation
When looking at the way
mypy
handles things, I noticed the following:f"hello"
) ⇒LiteralString
f"number {1}"
) ⇒str
My first commit (1ba5d0f) implements exactly this logic, except that we deal with string literals just like
infer_string_literal_expression
(if belowMAX_STRING_LITERAL_SIZE
, showLiteral["exact string"]
)Second Implementation
My second commit (90326ce) pushes things a bit further to handle cases where the expression within the
f-string
are all literal values (string representation known at static time).Here's an example of when this could happen in code:
As this can be sightly more costly (additional allocations), I don't know if we want this feature.
Test Plan
fstring_expression
covering all cases I can think of