Skip to content

Boolean expressions do not short circuit as expected #2444

Open
@AkshayWarrier

Description

@AkshayWarrier

I discovered this when I first ran

s: str
s = "    "
print(s.lstrip())

and it gave me this error

String index: 4 is out of Bounds

Looking at the implementation of _lpython_str_lstrip

@overload
def _lpython_str_lstrip(x: str) -> str:
    ind :i32
    ind = 0
    while ind < len(x) and x[ind] == ' ':
        ind += 1
    return x[ind :len(x)]

I realized that the and in while ind < len(x) and x[ind] == ' ': wasn't short circuiting as expected. It becomes more clear when running a minimal example

s: str
s = "    "
ind: i32 = 4
print((ind < 4) and (s[ind] == ' '))

This raises the index out of bounds error, because the second expression is being executed even though the first expression is False.
Similarly this raises an error as well

s: str
s = "    "
ind: i32 = 4
print((ind == 4) or (s[ind] == ' '))

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions