modularml / mojo

The Mojo Programming Language
https://docs.modular.com/mojo
Other
21.54k stars 2.51k forks source link

[BUG]: Conditional expression results in a bool type (inconsistent with python) #1767

Open davidbrownell opened 2 months ago

davidbrownell commented 2 months ago

Bug description

The following code in Mojo prints True:

fn main():
    let x = 0
    print(x or "hello")

In python, the following code prints hello:

print(0 or "hello")

Steps to reproduce

System information

- What OS did you install Mojo on? 
Ubuntu 22.04

- Provide version information for Mojo by pasting the output of `mojo -v`?
mojo 0.7.0 (af002202)

- Provide Modular CLI version by pasting the output of `modular -v`
modular 0.4.1 (2d8afe15)
laszlokindrat commented 2 months ago

We discussed the unexpected behavior of short circuiting conditional expressions in Mojo, such as the expression 0 or "hello" evaluating to a True value (of Bool type). Since Mojo is a statically typed language, it is not trivial to mimic Python’s behavior in this case, since the type of these expressions are not always obvious. In the future, we might be able to do something using existentials: the compiler could find the common traits (or methods) on the types of the two operands and emit something with that conforms to those. For now, we decided that we will not change the existing behavior until we have more dynamic features built out. However, we will document this behavior since it is a potentially confusing deviation from Python.

davidbrownell commented 2 months ago

Thank you for the information, Laszlo!