forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[mypyc] Implement the walrus operator (python#9624)
My assessment that this would not be too hard was accurate. Fixes mypyc/mypyc#765.
- Loading branch information
Showing
4 changed files
with
62 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
[case testWalrus1] | ||
from typing import Optional | ||
|
||
def foo(x: int) -> Optional[int]: | ||
if x < 0: | ||
return None | ||
return x | ||
|
||
def test(x: int) -> str: | ||
if (n := foo(x)) is not None: | ||
return str(x) | ||
else: | ||
return "<fail>" | ||
|
||
[file driver.py] | ||
from native import test | ||
|
||
assert test(10) == "10" | ||
assert test(-1) == "<fail>" | ||
|
||
|
||
[case testWalrus2] | ||
from typing import Optional, Tuple, List | ||
|
||
class Node: | ||
def __init__(self, val: int, next: Optional['Node']) -> None: | ||
self.val = val | ||
self.next = next | ||
|
||
def pairs(nobe: Optional[Node]) -> List[Tuple[int, int]]: | ||
if nobe is None: | ||
return [] | ||
l = [] | ||
while next := nobe.next: | ||
l.append((nobe.val, next.val)) | ||
nobe = next | ||
return l | ||
|
||
def make(l: List[int]) -> Optional[Node]: | ||
cur: Optional[Node] = None | ||
for x in reversed(l): | ||
cur = Node(x, cur) | ||
return cur | ||
|
||
[file driver.py] | ||
from native import Node, make, pairs | ||
|
||
assert pairs(make([1,2,3])) == [(1,2), (2,3)] | ||
assert pairs(make([1])) == [] | ||
assert pairs(make([])) == [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters