Skip to content

added __complex__ support - #3984

Open
aaishwarymishra wants to merge 2 commits into
ml-explore:mainfrom
aaishwarymishra:add-complex
Open

added __complex__ support#3984
aaishwarymishra wants to merge 2 commits into
ml-explore:mainfrom
aaishwarymishra:add-complex

Conversation

@aaishwarymishra

@aaishwarymishra aaishwarymishra commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

This pull request adds support for converting mx::array objects to Python complex numbers by implementing the

Please include a description of the problem or feature this PR is addressing. If there is a corresponding issue, include the issue #.

__complex__ method. It also extends the test suite to verify this new functionality, ensuring that both real and complex arrays behave as expected when converted to complex numbers.

New feature: Python complex conversion support

  • Added a __complex__ method to the mx::array Python bindings, allowing mx::array instances to be converted to Python complex numbers using the built-in complex() function.

Test improvements

  • Extended the test_to_scalar test to check that complex(mx.array(...)) returns the correct complex value for real and complex arrays, and raises a ValueError for non-scalar arrays.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

Part of the data-apis/array-api-compat#452 .

@aaishwarymishra

Copy link
Copy Markdown
Contributor Author

While working on test my linter were showing me warning that complex is not valid input for mlx array do you think we need to update mlx array arguments?

Comment thread python/src/array.cpp
.def(
"__complex__",
[](mx::array& a) {
auto value = PyComplex_AsCComplex(to_scalar(a).ptr());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can it be done with just return nb::handle(PyComplex_AsCComplex(to_scalar(a).ptr()))?

@zcbenz

zcbenz commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

While working on test my linter were showing me warning that complex is not valid input for mlx array do you think we need to update mlx array arguments?

I'm open to support complex as array input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants