Closed dscrofts closed 8 months ago
This is not how the match
statement works. int() as i
checks if selected
is an int
, and if so, binds that value to i
. int(i)
is a shorthand for this. Quoting from PEP636:
For many builtin classes (see PEP 634 for the whole list), you can use a positional parameter as a shorthand, writing
str(c)
rather thanstr() as c
.
The below code example shows that int(i)
does not raise a type error, and has the same semantics as int() as i
:
def f(selected: int | None):
match selected:
case int() as i:
print(i)
def f2(selected: int | None):
match selected:
case int(i):
print(i)
f(1)
f(None)
f2(1)
f2(None)
Prints:
1
1
@dosisod thank you for the clarification. I was under the impression that the shorthand code only worked for builtins and not optional types, but your code proves otherwise.
Has your issue already been fixed?
master
branch? See the docs for instructions on how to setup a local build of Refurb.The Bug
The following code:
Emits the following error:
But it should not be emitting an error because in this instance the code semantics would change.
int() as i
is used to match against integer values and bind the matched value to the variableselected
. Whereasint(i)
is a function call that tries to convert the value ofselected
to an integer. Ifselected
isNone
, it will raise aTypeError
becauseNone
cannot be converted to an integer.Version Info
Python Version
Python 3.12.2
Config File
Extra Info
None