Skip to content
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

allow casting optional type to numba concrete types #9161

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion numba/core/typing/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,10 @@ def typer(val):
sig = fnty.get_call_type(self.context, (val, types.DType(ty)),
{})
return sig.return_type
elif isinstance(val, (types.Number, types.Boolean, types.IntEnumMember)):
elif isinstance(val, (types.Number,
types.Boolean,
types.IntEnumMember,
types.Optional)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this permit something that is optional but not like a number?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In current mainline, we have this, so I think we allow casting optional to any type in the lowering level?

@lower_cast(types.Optional, types.Any)

Copy link
Contributor Author

@dlee992 dlee992 Aug 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR will let typeinfer also allow casting optional to any type (?) in the typing level, I think..

# Scalar constructor, e.g. np.int32(42)
return ty
elif isinstance(val, (types.NPDatetime, types.NPTimedelta)):
Expand Down
14 changes: 14 additions & 0 deletions numba/tests/test_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,20 @@ def work():
# incref being made on the returned None.
work()

def test_optional_to_int(self):
@njit
def foo(key):
d = {1:1}
value = d.get(key)
if value is None:
return None
else:
# allow using types.int64 as int for optional type
return types.int64(value)

for key in [1, 2]:
self.assertEqual(foo.py_func(key), foo(key))


if __name__ == '__main__':
unittest.main()
Loading